From abb7639394c4c2463dc19b82182b9bae43e365db Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Mon, 9 May 2016 16:54:39 -0700 Subject: [PATCH 1/9] Add router dependency --- glide.lock | 14 +- glide.yaml | 2 + vendor/github.com/gorilla/context/.travis.yml | 18 + vendor/github.com/gorilla/context/LICENSE | 27 + vendor/github.com/gorilla/context/README.md | 7 + vendor/github.com/gorilla/context/context.go | 143 ++ .../gorilla/context/context_test.go | 161 ++ vendor/github.com/gorilla/context/doc.go | 82 + vendor/github.com/gorilla/mux/.travis.yml | 17 + vendor/github.com/gorilla/mux/LICENSE | 27 + vendor/github.com/gorilla/mux/README.md | 242 +++ vendor/github.com/gorilla/mux/bench_test.go | 49 + vendor/github.com/gorilla/mux/doc.go | 206 +++ vendor/github.com/gorilla/mux/mux.go | 499 ++++++ vendor/github.com/gorilla/mux/mux_test.go | 1471 +++++++++++++++++ vendor/github.com/gorilla/mux/old_test.go | 710 ++++++++ vendor/github.com/gorilla/mux/regexp.go | 312 ++++ vendor/github.com/gorilla/mux/route.go | 634 +++++++ vendor/github.com/pkg/errors/README.md | 8 +- vendor/github.com/spf13/cobra/.travis.yml | 11 +- .../x/tools/go/gcimporter15/bexport_test.go | 55 +- .../x/tools/go/gcimporter15/bimport.go | 72 +- .../x/tools/go/gcimporter15/gcimporter.go | 3 +- .../x/tools/godoc/static/package.html | 16 +- .../golang.org/x/tools/godoc/static/static.go | 24 +- .../golang.org/x/tools/godoc/static/style.css | 8 + 26 files changed, 4778 insertions(+), 40 deletions(-) create mode 100644 vendor/github.com/gorilla/context/.travis.yml create mode 100644 vendor/github.com/gorilla/context/LICENSE create mode 100644 vendor/github.com/gorilla/context/README.md create mode 100644 vendor/github.com/gorilla/context/context.go create mode 100644 vendor/github.com/gorilla/context/context_test.go create mode 100644 vendor/github.com/gorilla/context/doc.go create mode 100644 vendor/github.com/gorilla/mux/.travis.yml create mode 100644 vendor/github.com/gorilla/mux/LICENSE create mode 100644 vendor/github.com/gorilla/mux/README.md create mode 100644 vendor/github.com/gorilla/mux/bench_test.go create mode 100644 vendor/github.com/gorilla/mux/doc.go create mode 100644 vendor/github.com/gorilla/mux/mux.go create mode 100644 vendor/github.com/gorilla/mux/mux_test.go create mode 100644 vendor/github.com/gorilla/mux/old_test.go create mode 100644 vendor/github.com/gorilla/mux/regexp.go create mode 100644 vendor/github.com/gorilla/mux/route.go diff --git a/glide.lock b/glide.lock index e59efaf747..a06d7e6594 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: b83f7fe2bc145c3d1fb1b4d2dfcd824133609907df0a90ca9372bd4d2edf34b6 -updated: 2016-05-04T13:23:16.671370976-07:00 +hash: 31c9b7e9f98ce4ccaadc502360c930f22151e9ccb77eba12f030fd87edfd8c9f +updated: 2016-05-09T16:58:07.015114036-07:00 imports: - name: github.com/apcera/termtables version: 683d3fb424194f29991b0442b37521de9bc9d66b @@ -8,20 +8,24 @@ imports: - term - name: github.com/golang/lint version: c7bacac2b21ca01afa1dee0acf64df3ce047c28f +- name: github.com/gorilla/context + version: a8d44e7d8e4d532b6a27a02dd82abb31cc1b01bd +- name: github.com/gorilla/mux + version: 9c19ed558d5df4da88e2ade9c8940d742aef0e7e - name: github.com/inconshreveable/mousetrap version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 - name: github.com/peterh/liner version: 0e4af131b90a9786839c8b1b01717be263e8555a - name: github.com/pkg/errors - version: 0d62637d0446292fceb852ab68e3ce6e07bddc00 + version: 502e17a0cb34bd200593552492e458d89cf6a64f - name: github.com/PuerkitoBio/pigeon version: a5221784523de14130c00a8c389148a1b2ad260c - name: github.com/spf13/cobra - version: 336d629de064dbb12166b46c06039dbcfb935de1 + version: 0f866a6211e33cde2091d9290c08f6afd6c9ebbc - name: github.com/spf13/pflag version: cb88ea77998c3f024757528e3305022ab50b43be - name: golang.org/x/tools - version: 0b2f4dcf4db5371000beb66b65cde17aa91a28a2 + version: 3f1f7eeff104d9ef829677f12b9780dfdd26a96a subpackages: - cmd/goimports devImports: [] diff --git a/glide.yaml b/glide.yaml index b092e75acd..232ebfdc9f 100644 --- a/glide.yaml +++ b/glide.yaml @@ -9,3 +9,5 @@ import: - package: github.com/peterh/liner - package: github.com/apcera/termtables - package: github.com/pkg/errors +- package: github.com/gorilla/mux +- package: github.com/gorilla/context diff --git a/vendor/github.com/gorilla/context/.travis.yml b/vendor/github.com/gorilla/context/.travis.yml new file mode 100644 index 0000000000..24882fc7b8 --- /dev/null +++ b/vendor/github.com/gorilla/context/.travis.yml @@ -0,0 +1,18 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.3 + - go: 1.4 + - go: 1.5 + - go: 1.6 + - go: tip + allow_failures: + - go: tip + +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go vet $(go list ./... | grep -v /vendor/) + - go test -v -race ./... diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE new file mode 100644 index 0000000000..0e5fb87280 --- /dev/null +++ b/vendor/github.com/gorilla/context/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. 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 Google Inc. 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 +OWNER 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. diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md new file mode 100644 index 0000000000..c60a31b053 --- /dev/null +++ b/vendor/github.com/gorilla/context/README.md @@ -0,0 +1,7 @@ +context +======= +[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) + +gorilla/context is a general purpose registry for global request variables. + +Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go new file mode 100644 index 0000000000..81cb128b19 --- /dev/null +++ b/vendor/github.com/gorilla/context/context.go @@ -0,0 +1,143 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context + +import ( + "net/http" + "sync" + "time" +) + +var ( + mutex sync.RWMutex + data = make(map[*http.Request]map[interface{}]interface{}) + datat = make(map[*http.Request]int64) +) + +// Set stores a value for a given key in a given request. +func Set(r *http.Request, key, val interface{}) { + mutex.Lock() + if data[r] == nil { + data[r] = make(map[interface{}]interface{}) + datat[r] = time.Now().Unix() + } + data[r][key] = val + mutex.Unlock() +} + +// Get returns a value stored for a given key in a given request. +func Get(r *http.Request, key interface{}) interface{} { + mutex.RLock() + if ctx := data[r]; ctx != nil { + value := ctx[key] + mutex.RUnlock() + return value + } + mutex.RUnlock() + return nil +} + +// GetOk returns stored value and presence state like multi-value return of map access. +func GetOk(r *http.Request, key interface{}) (interface{}, bool) { + mutex.RLock() + if _, ok := data[r]; ok { + value, ok := data[r][key] + mutex.RUnlock() + return value, ok + } + mutex.RUnlock() + return nil, false +} + +// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. +func GetAll(r *http.Request) map[interface{}]interface{} { + mutex.RLock() + if context, ok := data[r]; ok { + result := make(map[interface{}]interface{}, len(context)) + for k, v := range context { + result[k] = v + } + mutex.RUnlock() + return result + } + mutex.RUnlock() + return nil +} + +// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if +// the request was registered. +func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { + mutex.RLock() + context, ok := data[r] + result := make(map[interface{}]interface{}, len(context)) + for k, v := range context { + result[k] = v + } + mutex.RUnlock() + return result, ok +} + +// Delete removes a value stored for a given key in a given request. +func Delete(r *http.Request, key interface{}) { + mutex.Lock() + if data[r] != nil { + delete(data[r], key) + } + mutex.Unlock() +} + +// Clear removes all values stored for a given request. +// +// This is usually called by a handler wrapper to clean up request +// variables at the end of a request lifetime. See ClearHandler(). +func Clear(r *http.Request) { + mutex.Lock() + clear(r) + mutex.Unlock() +} + +// clear is Clear without the lock. +func clear(r *http.Request) { + delete(data, r) + delete(datat, r) +} + +// Purge removes request data stored for longer than maxAge, in seconds. +// It returns the amount of requests removed. +// +// If maxAge <= 0, all request data is removed. +// +// This is only used for sanity check: in case context cleaning was not +// properly set some request data can be kept forever, consuming an increasing +// amount of memory. In case this is detected, Purge() must be called +// periodically until the problem is fixed. +func Purge(maxAge int) int { + mutex.Lock() + count := 0 + if maxAge <= 0 { + count = len(data) + data = make(map[*http.Request]map[interface{}]interface{}) + datat = make(map[*http.Request]int64) + } else { + min := time.Now().Unix() - int64(maxAge) + for r := range data { + if datat[r] < min { + clear(r) + count++ + } + } + } + mutex.Unlock() + return count +} + +// ClearHandler wraps an http.Handler and clears request values at the end +// of a request lifetime. +func ClearHandler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer Clear(r) + h.ServeHTTP(w, r) + }) +} diff --git a/vendor/github.com/gorilla/context/context_test.go b/vendor/github.com/gorilla/context/context_test.go new file mode 100644 index 0000000000..9814c501e8 --- /dev/null +++ b/vendor/github.com/gorilla/context/context_test.go @@ -0,0 +1,161 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context + +import ( + "net/http" + "testing" +) + +type keyType int + +const ( + key1 keyType = iota + key2 +) + +func TestContext(t *testing.T) { + assertEqual := func(val interface{}, exp interface{}) { + if val != exp { + t.Errorf("Expected %v, got %v.", exp, val) + } + } + + r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + + // Get() + assertEqual(Get(r, key1), nil) + + // Set() + Set(r, key1, "1") + assertEqual(Get(r, key1), "1") + assertEqual(len(data[r]), 1) + + Set(r, key2, "2") + assertEqual(Get(r, key2), "2") + assertEqual(len(data[r]), 2) + + //GetOk + value, ok := GetOk(r, key1) + assertEqual(value, "1") + assertEqual(ok, true) + + value, ok = GetOk(r, "not exists") + assertEqual(value, nil) + assertEqual(ok, false) + + Set(r, "nil value", nil) + value, ok = GetOk(r, "nil value") + assertEqual(value, nil) + assertEqual(ok, true) + + // GetAll() + values := GetAll(r) + assertEqual(len(values), 3) + + // GetAll() for empty request + values = GetAll(emptyR) + if values != nil { + t.Error("GetAll didn't return nil value for invalid request") + } + + // GetAllOk() + values, ok = GetAllOk(r) + assertEqual(len(values), 3) + assertEqual(ok, true) + + // GetAllOk() for empty request + values, ok = GetAllOk(emptyR) + assertEqual(value, nil) + assertEqual(ok, false) + + // Delete() + Delete(r, key1) + assertEqual(Get(r, key1), nil) + assertEqual(len(data[r]), 2) + + Delete(r, key2) + assertEqual(Get(r, key2), nil) + assertEqual(len(data[r]), 1) + + // Clear() + Clear(r) + assertEqual(len(data), 0) +} + +func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { + <-wait + for i := 0; i < iterations; i++ { + Get(r, key) + } + done <- struct{}{} + +} + +func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { + <-wait + for i := 0; i < iterations; i++ { + Set(r, key, value) + } + done <- struct{}{} + +} + +func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { + + b.StopTimer() + r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + done := make(chan struct{}) + b.StartTimer() + + for i := 0; i < b.N; i++ { + wait := make(chan struct{}) + + for i := 0; i < numReaders; i++ { + go parallelReader(r, "test", iterations, wait, done) + } + + for i := 0; i < numWriters; i++ { + go parallelWriter(r, "test", "123", iterations, wait, done) + } + + close(wait) + + for i := 0; i < numReaders+numWriters; i++ { + <-done + } + + } + +} + +func BenchmarkMutexSameReadWrite1(b *testing.B) { + benchmarkMutex(b, 1, 1, 32) +} +func BenchmarkMutexSameReadWrite2(b *testing.B) { + benchmarkMutex(b, 2, 2, 32) +} +func BenchmarkMutexSameReadWrite4(b *testing.B) { + benchmarkMutex(b, 4, 4, 32) +} +func BenchmarkMutex1(b *testing.B) { + benchmarkMutex(b, 2, 8, 32) +} +func BenchmarkMutex2(b *testing.B) { + benchmarkMutex(b, 16, 4, 64) +} +func BenchmarkMutex3(b *testing.B) { + benchmarkMutex(b, 1, 2, 128) +} +func BenchmarkMutex4(b *testing.B) { + benchmarkMutex(b, 128, 32, 256) +} +func BenchmarkMutex5(b *testing.B) { + benchmarkMutex(b, 1024, 2048, 64) +} +func BenchmarkMutex6(b *testing.B) { + benchmarkMutex(b, 2048, 1024, 512) +} diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go new file mode 100644 index 0000000000..73c7400311 --- /dev/null +++ b/vendor/github.com/gorilla/context/doc.go @@ -0,0 +1,82 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package context stores values shared during a request lifetime. + +For example, a router can set variables extracted from the URL and later +application handlers can access those values, or it can be used to store +sessions values to be saved at the end of a request. There are several +others common uses. + +The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: + + http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 + +Here's the basic usage: first define the keys that you will need. The key +type is interface{} so a key can be of any type that supports equality. +Here we define a key using a custom int type to avoid name collisions: + + package foo + + import ( + "github.com/gorilla/context" + ) + + type key int + + const MyKey key = 0 + +Then set a variable. Variables are bound to an http.Request object, so you +need a request instance to set a value: + + context.Set(r, MyKey, "bar") + +The application can later access the variable using the same key you provided: + + func MyHandler(w http.ResponseWriter, r *http.Request) { + // val is "bar". + val := context.Get(r, foo.MyKey) + + // returns ("bar", true) + val, ok := context.GetOk(r, foo.MyKey) + // ... + } + +And that's all about the basic usage. We discuss some other ideas below. + +Any type can be stored in the context. To enforce a given type, make the key +private and wrap Get() and Set() to accept and return values of a specific +type: + + type key int + + const mykey key = 0 + + // GetMyKey returns a value for this package from the request values. + func GetMyKey(r *http.Request) SomeType { + if rv := context.Get(r, mykey); rv != nil { + return rv.(SomeType) + } + return nil + } + + // SetMyKey sets a value for this package in the request values. + func SetMyKey(r *http.Request, val SomeType) { + context.Set(r, mykey, val) + } + +Variables must be cleared at the end of a request, to remove all values +that were stored. This can be done in an http.Handler, after a request was +served. Just call Clear() passing the request: + + context.Clear(r) + +...or use ClearHandler(), which conveniently wraps an http.Handler to clear +variables at the end of a request lifetime. + +The Routers from the packages gorilla/mux and gorilla/pat call Clear() +so if you are using either of them you don't need to clear the context manually. +*/ +package context diff --git a/vendor/github.com/gorilla/mux/.travis.yml b/vendor/github.com/gorilla/mux/.travis.yml new file mode 100644 index 0000000000..f4084bd816 --- /dev/null +++ b/vendor/github.com/gorilla/mux/.travis.yml @@ -0,0 +1,17 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.2 + - go: 1.3 + - go: 1.4 + - go: 1.5 + - go: 1.6 + - go: tip + +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go tool vet . + - go test -v -race ./... diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE new file mode 100644 index 0000000000..0e5fb87280 --- /dev/null +++ b/vendor/github.com/gorilla/mux/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. 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 Google Inc. 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 +OWNER 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. diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md new file mode 100644 index 0000000000..9516c51916 --- /dev/null +++ b/vendor/github.com/gorilla/mux/README.md @@ -0,0 +1,242 @@ +mux +=== +[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) +[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) + +http://www.gorillatoolkit.org/pkg/mux + +Package `gorilla/mux` implements a request router and dispatcher. + +The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: + +* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. +* URL hosts and paths can have variables with an optional regular expression. +* Registered URLs can be built, or "reversed", which helps maintaining references to resources. +* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. +* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. + +Let's start registering a couple of URL paths and handlers: + +```go +func main() { + r := mux.NewRouter() + r.HandleFunc("/", HomeHandler) + r.HandleFunc("/products", ProductsHandler) + r.HandleFunc("/articles", ArticlesHandler) + http.Handle("/", r) +} +``` + +Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. + +Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: + +```go +r := mux.NewRouter() +r.HandleFunc("/products/{key}", ProductHandler) +r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) +r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) +``` + +The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: + +```go +vars := mux.Vars(request) +category := vars["category"] +``` + +And this is all you need to know about the basic usage. More advanced options are explained below. + +Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: + +```go +r := mux.NewRouter() +// Only matches if domain is "www.example.com". +r.Host("www.example.com") +// Matches a dynamic subdomain. +r.Host("{subdomain:[a-z]+}.domain.com") +``` + +There are several other matchers that can be added. To match path prefixes: + +```go +r.PathPrefix("/products/") +``` + +...or HTTP methods: + +```go +r.Methods("GET", "POST") +``` + +...or URL schemes: + +```go +r.Schemes("https") +``` + +...or header values: + +```go +r.Headers("X-Requested-With", "XMLHttpRequest") +``` + +...or query values: + +```go +r.Queries("key", "value") +``` + +...or to use a custom matcher function: + +```go +r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { + return r.ProtoMajor == 0 +}) +``` + +...and finally, it is possible to combine several matchers in a single route: + +```go +r.HandleFunc("/products", ProductsHandler). + Host("www.example.com"). + Methods("GET"). + Schemes("http") +``` + +Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". + +For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: + +```go +r := mux.NewRouter() +s := r.Host("www.example.com").Subrouter() +``` + +Then register routes in the subrouter: + +```go +s.HandleFunc("/products/", ProductsHandler) +s.HandleFunc("/products/{key}", ProductHandler) +s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) +``` + +The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. + +Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. + +There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: + +```go +r := mux.NewRouter() +s := r.PathPrefix("/products").Subrouter() +// "/products/" +s.HandleFunc("/", ProductsHandler) +// "/products/{key}/" +s.HandleFunc("/{key}/", ProductHandler) +// "/products/{key}/details" +s.HandleFunc("/{key}/details", ProductDetailsHandler) +``` + +Now let's see how to build registered URLs. + +Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: + +```go +r := mux.NewRouter() +r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). + Name("article") +``` + +To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: + +```go +url, err := r.Get("article").URL("category", "technology", "id", "42") +``` + +...and the result will be a `url.URL` with the following path: + +``` +"/articles/technology/42" +``` + +This also works for host variables: + +```go +r := mux.NewRouter() +r.Host("{subdomain}.domain.com"). + Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + +// url.String() will be "http://news.domain.com/articles/technology/42" +url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") +``` + +All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. + +Regex support also exists for matching Headers within a route. For example, we could do: + +```go +r.HeadersRegexp("Content-Type", "application/(text|json)") +``` + +...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` + +There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: + +```go +// "http://news.domain.com/" +host, err := r.Get("article").URLHost("subdomain", "news") + +// "/articles/technology/42" +path, err := r.Get("article").URLPath("category", "technology", "id", "42") +``` + +And if you use subrouters, host and path defined separately can be built as well: + +```go +r := mux.NewRouter() +s := r.Host("{subdomain}.domain.com").Subrouter() +s.Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + +// "http://news.domain.com/articles/technology/42" +url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") +``` + +## Full Example + +Here's a complete, runnable example of a small `mux` based server: + +```go +package main + +import ( + "net/http" + + "github.com/gorilla/mux" +) + +func YourHandler(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("Gorilla!\n")) +} + +func main() { + r := mux.NewRouter() + // Routes consist of a path and a handler function. + r.HandleFunc("/", YourHandler) + + // Bind to a port and pass our router in + http.ListenAndServe(":8000", r) +} +``` + +## License + +BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/mux/bench_test.go b/vendor/github.com/gorilla/mux/bench_test.go new file mode 100644 index 0000000000..946289b92b --- /dev/null +++ b/vendor/github.com/gorilla/mux/bench_test.go @@ -0,0 +1,49 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func BenchmarkMux(b *testing.B) { + router := new(Router) + handler := func(w http.ResponseWriter, r *http.Request) {} + router.HandleFunc("/v1/{v1}", handler) + + request, _ := http.NewRequest("GET", "/v1/anything", nil) + for i := 0; i < b.N; i++ { + router.ServeHTTP(nil, request) + } +} + +func BenchmarkMuxAlternativeInRegexp(b *testing.B) { + router := new(Router) + handler := func(w http.ResponseWriter, r *http.Request) {} + router.HandleFunc("/v1/{v1:(a|b)}", handler) + + requestA, _ := http.NewRequest("GET", "/v1/a", nil) + requestB, _ := http.NewRequest("GET", "/v1/b", nil) + for i := 0; i < b.N; i++ { + router.ServeHTTP(nil, requestA) + router.ServeHTTP(nil, requestB) + } +} + +func BenchmarkManyPathVariables(b *testing.B) { + router := new(Router) + handler := func(w http.ResponseWriter, r *http.Request) {} + router.HandleFunc("/v1/{v1}/{v2}/{v3}/{v4}/{v5}", handler) + + matchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4/5", nil) + notMatchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4", nil) + recorder := httptest.NewRecorder() + for i := 0; i < b.N; i++ { + router.ServeHTTP(nil, matchingRequest) + router.ServeHTTP(recorder, notMatchingRequest) + } +} diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go new file mode 100644 index 0000000000..835f5342eb --- /dev/null +++ b/vendor/github.com/gorilla/mux/doc.go @@ -0,0 +1,206 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package mux implements a request router and dispatcher. + +The name mux stands for "HTTP request multiplexer". Like the standard +http.ServeMux, mux.Router matches incoming requests against a list of +registered routes and calls a handler for the route that matches the URL +or other conditions. The main features are: + + * Requests can be matched based on URL host, path, path prefix, schemes, + header and query values, HTTP methods or using custom matchers. + * URL hosts and paths can have variables with an optional regular + expression. + * Registered URLs can be built, or "reversed", which helps maintaining + references to resources. + * Routes can be used as subrouters: nested routes are only tested if the + parent route matches. This is useful to define groups of routes that + share common conditions like a host, a path prefix or other repeated + attributes. As a bonus, this optimizes request matching. + * It implements the http.Handler interface so it is compatible with the + standard http.ServeMux. + +Let's start registering a couple of URL paths and handlers: + + func main() { + r := mux.NewRouter() + r.HandleFunc("/", HomeHandler) + r.HandleFunc("/products", ProductsHandler) + r.HandleFunc("/articles", ArticlesHandler) + http.Handle("/", r) + } + +Here we register three routes mapping URL paths to handlers. This is +equivalent to how http.HandleFunc() works: if an incoming request URL matches +one of the paths, the corresponding handler is called passing +(http.ResponseWriter, *http.Request) as parameters. + +Paths can have variables. They are defined using the format {name} or +{name:pattern}. If a regular expression pattern is not defined, the matched +variable will be anything until the next slash. For example: + + r := mux.NewRouter() + r.HandleFunc("/products/{key}", ProductHandler) + r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) + r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) + +The names are used to create a map of route variables which can be retrieved +calling mux.Vars(): + + vars := mux.Vars(request) + category := vars["category"] + +And this is all you need to know about the basic usage. More advanced options +are explained below. + +Routes can also be restricted to a domain or subdomain. Just define a host +pattern to be matched. They can also have variables: + + r := mux.NewRouter() + // Only matches if domain is "www.example.com". + r.Host("www.example.com") + // Matches a dynamic subdomain. + r.Host("{subdomain:[a-z]+}.domain.com") + +There are several other matchers that can be added. To match path prefixes: + + r.PathPrefix("/products/") + +...or HTTP methods: + + r.Methods("GET", "POST") + +...or URL schemes: + + r.Schemes("https") + +...or header values: + + r.Headers("X-Requested-With", "XMLHttpRequest") + +...or query values: + + r.Queries("key", "value") + +...or to use a custom matcher function: + + r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { + return r.ProtoMajor == 0 + }) + +...and finally, it is possible to combine several matchers in a single route: + + r.HandleFunc("/products", ProductsHandler). + Host("www.example.com"). + Methods("GET"). + Schemes("http") + +Setting the same matching conditions again and again can be boring, so we have +a way to group several routes that share the same requirements. +We call it "subrouting". + +For example, let's say we have several URLs that should only match when the +host is "www.example.com". Create a route for that host and get a "subrouter" +from it: + + r := mux.NewRouter() + s := r.Host("www.example.com").Subrouter() + +Then register routes in the subrouter: + + s.HandleFunc("/products/", ProductsHandler) + s.HandleFunc("/products/{key}", ProductHandler) + s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) + +The three URL paths we registered above will only be tested if the domain is +"www.example.com", because the subrouter is tested first. This is not +only convenient, but also optimizes request matching. You can create +subrouters combining any attribute matchers accepted by a route. + +Subrouters can be used to create domain or path "namespaces": you define +subrouters in a central place and then parts of the app can register its +paths relatively to a given subrouter. + +There's one more thing about subroutes. When a subrouter has a path prefix, +the inner routes use it as base for their paths: + + r := mux.NewRouter() + s := r.PathPrefix("/products").Subrouter() + // "/products/" + s.HandleFunc("/", ProductsHandler) + // "/products/{key}/" + s.HandleFunc("/{key}/", ProductHandler) + // "/products/{key}/details" + s.HandleFunc("/{key}/details", ProductDetailsHandler) + +Now let's see how to build registered URLs. + +Routes can be named. All routes that define a name can have their URLs built, +or "reversed". We define a name calling Name() on a route. For example: + + r := mux.NewRouter() + r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). + Name("article") + +To build a URL, get the route and call the URL() method, passing a sequence of +key/value pairs for the route variables. For the previous route, we would do: + + url, err := r.Get("article").URL("category", "technology", "id", "42") + +...and the result will be a url.URL with the following path: + + "/articles/technology/42" + +This also works for host variables: + + r := mux.NewRouter() + r.Host("{subdomain}.domain.com"). + Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + + // url.String() will be "http://news.domain.com/articles/technology/42" + url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") + +All variables defined in the route are required, and their values must +conform to the corresponding patterns. These requirements guarantee that a +generated URL will always match a registered route -- the only exception is +for explicitly defined "build-only" routes which never match. + +Regex support also exists for matching Headers within a route. For example, we could do: + + r.HeadersRegexp("Content-Type", "application/(text|json)") + +...and the route will match both requests with a Content-Type of `application/json` as well as +`application/text` + +There's also a way to build only the URL host or path for a route: +use the methods URLHost() or URLPath() instead. For the previous route, +we would do: + + // "http://news.domain.com/" + host, err := r.Get("article").URLHost("subdomain", "news") + + // "/articles/technology/42" + path, err := r.Get("article").URLPath("category", "technology", "id", "42") + +And if you use subrouters, host and path defined separately can be built +as well: + + r := mux.NewRouter() + s := r.Host("{subdomain}.domain.com").Subrouter() + s.Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + + // "http://news.domain.com/articles/technology/42" + url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") +*/ +package mux diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go new file mode 100644 index 0000000000..94f5ddd9c7 --- /dev/null +++ b/vendor/github.com/gorilla/mux/mux.go @@ -0,0 +1,499 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "errors" + "fmt" + "net/http" + "path" + "regexp" + + "github.com/gorilla/context" +) + +// NewRouter returns a new router instance. +func NewRouter() *Router { + return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} +} + +// Router registers routes to be matched and dispatches a handler. +// +// It implements the http.Handler interface, so it can be registered to serve +// requests: +// +// var router = mux.NewRouter() +// +// func main() { +// http.Handle("/", router) +// } +// +// Or, for Google App Engine, register it in a init() function: +// +// func init() { +// http.Handle("/", router) +// } +// +// This will send all incoming requests to the router. +type Router struct { + // Configurable Handler to be used when no route matches. + NotFoundHandler http.Handler + // Parent route, if this is a subrouter. + parent parentRoute + // Routes to be matched, in order. + routes []*Route + // Routes by name for URL building. + namedRoutes map[string]*Route + // See Router.StrictSlash(). This defines the flag for new routes. + strictSlash bool + // See Router.SkipClean(). This defines the flag for new routes. + skipClean bool + // If true, do not clear the request context after handling the request + KeepContext bool +} + +// Match matches registered routes against the request. +func (r *Router) Match(req *http.Request, match *RouteMatch) bool { + for _, route := range r.routes { + if route.Match(req, match) { + return true + } + } + + // Closest match for a router (includes sub-routers) + if r.NotFoundHandler != nil { + match.Handler = r.NotFoundHandler + return true + } + return false +} + +// ServeHTTP dispatches the handler registered in the matched route. +// +// When there is a match, the route variables can be retrieved calling +// mux.Vars(request). +func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if !r.skipClean { + // Clean path to canonical form and redirect. + if p := cleanPath(req.URL.Path); p != req.URL.Path { + + // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. + // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: + // http://code.google.com/p/go/issues/detail?id=5252 + url := *req.URL + url.Path = p + p = url.String() + + w.Header().Set("Location", p) + w.WriteHeader(http.StatusMovedPermanently) + return + } + } + var match RouteMatch + var handler http.Handler + if r.Match(req, &match) { + handler = match.Handler + setVars(req, match.Vars) + setCurrentRoute(req, match.Route) + } + if handler == nil { + handler = http.NotFoundHandler() + } + if !r.KeepContext { + defer context.Clear(req) + } + handler.ServeHTTP(w, req) +} + +// Get returns a route registered with the given name. +func (r *Router) Get(name string) *Route { + return r.getNamedRoutes()[name] +} + +// GetRoute returns a route registered with the given name. This method +// was renamed to Get() and remains here for backwards compatibility. +func (r *Router) GetRoute(name string) *Route { + return r.getNamedRoutes()[name] +} + +// StrictSlash defines the trailing slash behavior for new routes. The initial +// value is false. +// +// When true, if the route path is "/path/", accessing "/path" will redirect +// to the former and vice versa. In other words, your application will always +// see the path as specified in the route. +// +// When false, if the route path is "/path", accessing "/path/" will not match +// this route and vice versa. +// +// Special case: when a route sets a path prefix using the PathPrefix() method, +// strict slash is ignored for that route because the redirect behavior can't +// be determined from a prefix alone. However, any subrouters created from that +// route inherit the original StrictSlash setting. +func (r *Router) StrictSlash(value bool) *Router { + r.strictSlash = value + return r +} + +// SkipClean defines the path cleaning behaviour for new routes. The initial +// value is false. Users should be careful about which routes are not cleaned +// +// When true, if the route path is "/path//to", it will remain with the double +// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ +// +// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will +// become /fetch/http/xkcd.com/534 +func (r *Router) SkipClean(value bool) *Router { + r.skipClean = value + return r +} + +// ---------------------------------------------------------------------------- +// parentRoute +// ---------------------------------------------------------------------------- + +// getNamedRoutes returns the map where named routes are registered. +func (r *Router) getNamedRoutes() map[string]*Route { + if r.namedRoutes == nil { + if r.parent != nil { + r.namedRoutes = r.parent.getNamedRoutes() + } else { + r.namedRoutes = make(map[string]*Route) + } + } + return r.namedRoutes +} + +// getRegexpGroup returns regexp definitions from the parent route, if any. +func (r *Router) getRegexpGroup() *routeRegexpGroup { + if r.parent != nil { + return r.parent.getRegexpGroup() + } + return nil +} + +func (r *Router) buildVars(m map[string]string) map[string]string { + if r.parent != nil { + m = r.parent.buildVars(m) + } + return m +} + +// ---------------------------------------------------------------------------- +// Route factories +// ---------------------------------------------------------------------------- + +// NewRoute registers an empty route. +func (r *Router) NewRoute() *Route { + route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean} + r.routes = append(r.routes, route) + return route +} + +// Handle registers a new route with a matcher for the URL path. +// See Route.Path() and Route.Handler(). +func (r *Router) Handle(path string, handler http.Handler) *Route { + return r.NewRoute().Path(path).Handler(handler) +} + +// HandleFunc registers a new route with a matcher for the URL path. +// See Route.Path() and Route.HandlerFunc(). +func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, + *http.Request)) *Route { + return r.NewRoute().Path(path).HandlerFunc(f) +} + +// Headers registers a new route with a matcher for request header values. +// See Route.Headers(). +func (r *Router) Headers(pairs ...string) *Route { + return r.NewRoute().Headers(pairs...) +} + +// Host registers a new route with a matcher for the URL host. +// See Route.Host(). +func (r *Router) Host(tpl string) *Route { + return r.NewRoute().Host(tpl) +} + +// MatcherFunc registers a new route with a custom matcher function. +// See Route.MatcherFunc(). +func (r *Router) MatcherFunc(f MatcherFunc) *Route { + return r.NewRoute().MatcherFunc(f) +} + +// Methods registers a new route with a matcher for HTTP methods. +// See Route.Methods(). +func (r *Router) Methods(methods ...string) *Route { + return r.NewRoute().Methods(methods...) +} + +// Path registers a new route with a matcher for the URL path. +// See Route.Path(). +func (r *Router) Path(tpl string) *Route { + return r.NewRoute().Path(tpl) +} + +// PathPrefix registers a new route with a matcher for the URL path prefix. +// See Route.PathPrefix(). +func (r *Router) PathPrefix(tpl string) *Route { + return r.NewRoute().PathPrefix(tpl) +} + +// Queries registers a new route with a matcher for URL query values. +// See Route.Queries(). +func (r *Router) Queries(pairs ...string) *Route { + return r.NewRoute().Queries(pairs...) +} + +// Schemes registers a new route with a matcher for URL schemes. +// See Route.Schemes(). +func (r *Router) Schemes(schemes ...string) *Route { + return r.NewRoute().Schemes(schemes...) +} + +// BuildVarsFunc registers a new route with a custom function for modifying +// route variables before building a URL. +func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { + return r.NewRoute().BuildVarsFunc(f) +} + +// Walk walks the router and all its sub-routers, calling walkFn for each route +// in the tree. The routes are walked in the order they were added. Sub-routers +// are explored depth-first. +func (r *Router) Walk(walkFn WalkFunc) error { + return r.walk(walkFn, []*Route{}) +} + +// SkipRouter is used as a return value from WalkFuncs to indicate that the +// router that walk is about to descend down to should be skipped. +var SkipRouter = errors.New("skip this router") + +// WalkFunc is the type of the function called for each route visited by Walk. +// At every invocation, it is given the current route, and the current router, +// and a list of ancestor routes that lead to the current route. +type WalkFunc func(route *Route, router *Router, ancestors []*Route) error + +func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { + for _, t := range r.routes { + if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" { + continue + } + + err := walkFn(t, r, ancestors) + if err == SkipRouter { + continue + } + for _, sr := range t.matchers { + if h, ok := sr.(*Router); ok { + err := h.walk(walkFn, ancestors) + if err != nil { + return err + } + } + } + if h, ok := t.handler.(*Router); ok { + ancestors = append(ancestors, t) + err := h.walk(walkFn, ancestors) + if err != nil { + return err + } + ancestors = ancestors[:len(ancestors)-1] + } + } + return nil +} + +// ---------------------------------------------------------------------------- +// Context +// ---------------------------------------------------------------------------- + +// RouteMatch stores information about a matched route. +type RouteMatch struct { + Route *Route + Handler http.Handler + Vars map[string]string +} + +type contextKey int + +const ( + varsKey contextKey = iota + routeKey +) + +// Vars returns the route variables for the current request, if any. +func Vars(r *http.Request) map[string]string { + if rv := context.Get(r, varsKey); rv != nil { + return rv.(map[string]string) + } + return nil +} + +// CurrentRoute returns the matched route for the current request, if any. +// This only works when called inside the handler of the matched route +// because the matched route is stored in the request context which is cleared +// after the handler returns, unless the KeepContext option is set on the +// Router. +func CurrentRoute(r *http.Request) *Route { + if rv := context.Get(r, routeKey); rv != nil { + return rv.(*Route) + } + return nil +} + +func setVars(r *http.Request, val interface{}) { + if val != nil { + context.Set(r, varsKey, val) + } +} + +func setCurrentRoute(r *http.Request, val interface{}) { + if val != nil { + context.Set(r, routeKey, val) + } +} + +// ---------------------------------------------------------------------------- +// Helpers +// ---------------------------------------------------------------------------- + +// cleanPath returns the canonical path for p, eliminating . and .. elements. +// Borrowed from the net/http package. +func cleanPath(p string) string { + if p == "" { + return "/" + } + if p[0] != '/' { + p = "/" + p + } + np := path.Clean(p) + // path.Clean removes trailing slash except for root; + // put the trailing slash back if necessary. + if p[len(p)-1] == '/' && np != "/" { + np += "/" + } + + return np +} + +// uniqueVars returns an error if two slices contain duplicated strings. +func uniqueVars(s1, s2 []string) error { + for _, v1 := range s1 { + for _, v2 := range s2 { + if v1 == v2 { + return fmt.Errorf("mux: duplicated route variable %q", v2) + } + } + } + return nil +} + +// checkPairs returns the count of strings passed in, and an error if +// the count is not an even number. +func checkPairs(pairs ...string) (int, error) { + length := len(pairs) + if length%2 != 0 { + return length, fmt.Errorf( + "mux: number of parameters must be multiple of 2, got %v", pairs) + } + return length, nil +} + +// mapFromPairsToString converts variadic string parameters to a +// string to string map. +func mapFromPairsToString(pairs ...string) (map[string]string, error) { + length, err := checkPairs(pairs...) + if err != nil { + return nil, err + } + m := make(map[string]string, length/2) + for i := 0; i < length; i += 2 { + m[pairs[i]] = pairs[i+1] + } + return m, nil +} + +// mapFromPairsToRegex converts variadic string paramers to a +// string to regex map. +func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { + length, err := checkPairs(pairs...) + if err != nil { + return nil, err + } + m := make(map[string]*regexp.Regexp, length/2) + for i := 0; i < length; i += 2 { + regex, err := regexp.Compile(pairs[i+1]) + if err != nil { + return nil, err + } + m[pairs[i]] = regex + } + return m, nil +} + +// matchInArray returns true if the given string value is in the array. +func matchInArray(arr []string, value string) bool { + for _, v := range arr { + if v == value { + return true + } + } + return false +} + +// matchMapWithString returns true if the given key/value pairs exist in a given map. +func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { + for k, v := range toCheck { + // Check if key exists. + if canonicalKey { + k = http.CanonicalHeaderKey(k) + } + if values := toMatch[k]; values == nil { + return false + } else if v != "" { + // If value was defined as an empty string we only check that the + // key exists. Otherwise we also check for equality. + valueExists := false + for _, value := range values { + if v == value { + valueExists = true + break + } + } + if !valueExists { + return false + } + } + } + return true +} + +// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against +// the given regex +func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { + for k, v := range toCheck { + // Check if key exists. + if canonicalKey { + k = http.CanonicalHeaderKey(k) + } + if values := toMatch[k]; values == nil { + return false + } else if v != nil { + // If value was defined as an empty string we only check that the + // key exists. Otherwise we also check for equality. + valueExists := false + for _, value := range values { + if v.MatchString(value) { + valueExists = true + break + } + } + if !valueExists { + return false + } + } + } + return true +} diff --git a/vendor/github.com/gorilla/mux/mux_test.go b/vendor/github.com/gorilla/mux/mux_test.go new file mode 100644 index 0000000000..777d063c05 --- /dev/null +++ b/vendor/github.com/gorilla/mux/mux_test.go @@ -0,0 +1,1471 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "fmt" + "net/http" + "strings" + "testing" + + "github.com/gorilla/context" +) + +func (r *Route) GoString() string { + matchers := make([]string, len(r.matchers)) + for i, m := range r.matchers { + matchers[i] = fmt.Sprintf("%#v", m) + } + return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", ")) +} + +func (r *routeRegexp) GoString() string { + return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR) +} + +type routeTest struct { + title string // title of the test + route *Route // the route being tested + request *http.Request // a request to test the route + vars map[string]string // the expected vars of the match + host string // the expected host of the match + path string // the expected path of the match + path_template string // the expected path template to match + host_template string // the expected host template to match + shouldMatch bool // whether the request is expected to match the route at all + shouldRedirect bool // whether the request should result in a redirect +} + +func TestHost(t *testing.T) { + // newRequestHost a new request with a method, url, and host header + newRequestHost := func(method, url, host string) *http.Request { + req, err := http.NewRequest(method, url, nil) + if err != nil { + panic(err) + } + req.Host = host + return req + } + + tests := []routeTest{ + { + title: "Host route match", + route: new(Route).Host("aaa.bbb.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{}, + host: "aaa.bbb.ccc", + path: "", + shouldMatch: true, + }, + { + title: "Host route, wrong host in request URL", + route: new(Route).Host("aaa.bbb.ccc"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{}, + host: "aaa.bbb.ccc", + path: "", + shouldMatch: false, + }, + { + title: "Host route with port, match", + route: new(Route).Host("aaa.bbb.ccc:1234"), + request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), + vars: map[string]string{}, + host: "aaa.bbb.ccc:1234", + path: "", + shouldMatch: true, + }, + { + title: "Host route with port, wrong port in request URL", + route: new(Route).Host("aaa.bbb.ccc:1234"), + request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), + vars: map[string]string{}, + host: "aaa.bbb.ccc:1234", + path: "", + shouldMatch: false, + }, + { + title: "Host route, match with host in request header", + route: new(Route).Host("aaa.bbb.ccc"), + request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), + vars: map[string]string{}, + host: "aaa.bbb.ccc", + path: "", + shouldMatch: true, + }, + { + title: "Host route, wrong host in request header", + route: new(Route).Host("aaa.bbb.ccc"), + request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), + vars: map[string]string{}, + host: "aaa.bbb.ccc", + path: "", + shouldMatch: false, + }, + // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, + { + title: "Host route with port, wrong host in request header", + route: new(Route).Host("aaa.bbb.ccc:1234"), + request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), + vars: map[string]string{}, + host: "aaa.bbb.ccc:1234", + path: "", + shouldMatch: false, + }, + { + title: "Host route with pattern, match", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `aaa.{v1:[a-z]{3}}.ccc`, + shouldMatch: true, + }, + { + title: "Host route with pattern, additional capturing group, match", + route: new(Route).Host("aaa.{v1:[a-z]{2}(b|c)}.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `aaa.{v1:[a-z]{2}(b|c)}.ccc`, + shouldMatch: true, + }, + { + title: "Host route with pattern, wrong host in request URL", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{"v1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `aaa.{v1:[a-z]{3}}.ccc`, + shouldMatch: false, + }, + { + title: "Host route with multiple patterns, match", + route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, + shouldMatch: true, + }, + { + title: "Host route with multiple patterns, wrong host in request URL", + route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, + shouldMatch: false, + }, + { + title: "Host route with hyphenated name and pattern, match", + route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v-1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `aaa.{v-1:[a-z]{3}}.ccc`, + shouldMatch: true, + }, + { + title: "Host route with hyphenated name and pattern, additional capturing group, match", + route: new(Route).Host("aaa.{v-1:[a-z]{2}(b|c)}.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v-1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `aaa.{v-1:[a-z]{2}(b|c)}.ccc`, + shouldMatch: true, + }, + { + title: "Host route with multiple hyphenated names and patterns, match", + route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"}, + host: "aaa.bbb.ccc", + path: "", + host_template: `{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}`, + shouldMatch: true, + }, + { + title: "Path route with single pattern with pipe, match", + route: new(Route).Path("/{category:a|b/c}"), + request: newRequest("GET", "http://localhost/a"), + vars: map[string]string{"category": "a"}, + host: "", + path: "/a", + path_template: `/{category:a|b/c}`, + shouldMatch: true, + }, + { + title: "Path route with single pattern with pipe, match", + route: new(Route).Path("/{category:a|b/c}"), + request: newRequest("GET", "http://localhost/b/c"), + vars: map[string]string{"category": "b/c"}, + host: "", + path: "/b/c", + path_template: `/{category:a|b/c}`, + shouldMatch: true, + }, + { + title: "Path route with multiple patterns with pipe, match", + route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), + request: newRequest("GET", "http://localhost/a/product_name/1"), + vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, + host: "", + path: "/a/product_name/1", + path_template: `/{category:a|b/c}/{product}/{id:[0-9]+}`, + shouldMatch: true, + }, + { + title: "Path route with multiple patterns with pipe, match", + route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), + request: newRequest("GET", "http://localhost/b/c/product_name/1"), + vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"}, + host: "", + path: "/b/c/product_name/1", + path_template: `/{category:a|b/c}/{product}/{id:[0-9]+}`, + shouldMatch: true, + }, + } + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestPath(t *testing.T) { + tests := []routeTest{ + { + title: "Path route, match", + route: new(Route).Path("/111/222/333"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{}, + host: "", + path: "/111/222/333", + shouldMatch: true, + }, + { + title: "Path route, match with trailing slash in request and path", + route: new(Route).Path("/111/"), + request: newRequest("GET", "http://localhost/111/"), + vars: map[string]string{}, + host: "", + path: "/111/", + shouldMatch: true, + }, + { + title: "Path route, do not match with trailing slash in path", + route: new(Route).Path("/111/"), + request: newRequest("GET", "http://localhost/111"), + vars: map[string]string{}, + host: "", + path: "/111", + path_template: `/111/`, + shouldMatch: false, + }, + { + title: "Path route, do not match with trailing slash in request", + route: new(Route).Path("/111"), + request: newRequest("GET", "http://localhost/111/"), + vars: map[string]string{}, + host: "", + path: "/111/", + path_template: `/111`, + shouldMatch: false, + }, + { + title: "Path route, wrong path in request in request URL", + route: new(Route).Path("/111/222/333"), + request: newRequest("GET", "http://localhost/1/2/3"), + vars: map[string]string{}, + host: "", + path: "/111/222/333", + shouldMatch: false, + }, + { + title: "Path route with pattern, match", + route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v1": "222"}, + host: "", + path: "/111/222/333", + path_template: `/111/{v1:[0-9]{3}}/333`, + shouldMatch: true, + }, + { + title: "Path route with pattern, URL in request does not match", + route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), + request: newRequest("GET", "http://localhost/111/aaa/333"), + vars: map[string]string{"v1": "222"}, + host: "", + path: "/111/222/333", + path_template: `/111/{v1:[0-9]{3}}/333`, + shouldMatch: false, + }, + { + title: "Path route with multiple patterns, match", + route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, + host: "", + path: "/111/222/333", + path_template: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`, + shouldMatch: true, + }, + { + title: "Path route with multiple patterns, URL in request does not match", + route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/aaa/333"), + vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, + host: "", + path: "/111/222/333", + path_template: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`, + shouldMatch: false, + }, + { + title: "Path route with multiple patterns with pipe, match", + route: new(Route).Path("/{category:a|(b/c)}/{product}/{id:[0-9]+}"), + request: newRequest("GET", "http://localhost/a/product_name/1"), + vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, + host: "", + path: "/a/product_name/1", + path_template: `/{category:a|(b/c)}/{product}/{id:[0-9]+}`, + shouldMatch: true, + }, + { + title: "Path route with hyphenated name and pattern, match", + route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v-1": "222"}, + host: "", + path: "/111/222/333", + path_template: `/111/{v-1:[0-9]{3}}/333`, + shouldMatch: true, + }, + { + title: "Path route with multiple hyphenated names and patterns, match", + route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"}, + host: "", + path: "/111/222/333", + path_template: `/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}`, + shouldMatch: true, + }, + { + title: "Path route with multiple hyphenated names and patterns with pipe, match", + route: new(Route).Path("/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}"), + request: newRequest("GET", "http://localhost/a/product_name/1"), + vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"}, + host: "", + path: "/a/product_name/1", + path_template: `/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}`, + shouldMatch: true, + }, + { + title: "Path route with multiple hyphenated names and patterns with pipe and case insensitive, match", + route: new(Route).Path("/{type:(?i:daily|mini|variety)}-{date:\\d{4,4}-\\d{2,2}-\\d{2,2}}"), + request: newRequest("GET", "http://localhost/daily-2016-01-01"), + vars: map[string]string{"type": "daily", "date": "2016-01-01"}, + host: "", + path: "/daily-2016-01-01", + path_template: `/{type:(?i:daily|mini|variety)}-{date:\d{4,4}-\d{2,2}-\d{2,2}}`, + shouldMatch: true, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestPathPrefix(t *testing.T) { + tests := []routeTest{ + { + title: "PathPrefix route, match", + route: new(Route).PathPrefix("/111"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{}, + host: "", + path: "/111", + shouldMatch: true, + }, + { + title: "PathPrefix route, match substring", + route: new(Route).PathPrefix("/1"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{}, + host: "", + path: "/1", + shouldMatch: true, + }, + { + title: "PathPrefix route, URL prefix in request does not match", + route: new(Route).PathPrefix("/111"), + request: newRequest("GET", "http://localhost/1/2/3"), + vars: map[string]string{}, + host: "", + path: "/111", + shouldMatch: false, + }, + { + title: "PathPrefix route with pattern, match", + route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v1": "222"}, + host: "", + path: "/111/222", + path_template: `/111/{v1:[0-9]{3}}`, + shouldMatch: true, + }, + { + title: "PathPrefix route with pattern, URL prefix in request does not match", + route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/aaa/333"), + vars: map[string]string{"v1": "222"}, + host: "", + path: "/111/222", + path_template: `/111/{v1:[0-9]{3}}`, + shouldMatch: false, + }, + { + title: "PathPrefix route with multiple patterns, match", + route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/222/333"), + vars: map[string]string{"v1": "111", "v2": "222"}, + host: "", + path: "/111/222", + path_template: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`, + shouldMatch: true, + }, + { + title: "PathPrefix route with multiple patterns, URL prefix in request does not match", + route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), + request: newRequest("GET", "http://localhost/111/aaa/333"), + vars: map[string]string{"v1": "111", "v2": "222"}, + host: "", + path: "/111/222", + path_template: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`, + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestHostPath(t *testing.T) { + tests := []routeTest{ + { + title: "Host and Path route, match", + route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{}, + host: "", + path: "", + path_template: `/111/222/333`, + host_template: `aaa.bbb.ccc`, + shouldMatch: true, + }, + { + title: "Host and Path route, wrong host in request URL", + route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{}, + host: "", + path: "", + path_template: `/111/222/333`, + host_template: `aaa.bbb.ccc`, + shouldMatch: false, + }, + { + title: "Host and Path route with pattern, match", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v1": "bbb", "v2": "222"}, + host: "aaa.bbb.ccc", + path: "/111/222/333", + path_template: `/111/{v2:[0-9]{3}}/333`, + host_template: `aaa.{v1:[a-z]{3}}.ccc`, + shouldMatch: true, + }, + { + title: "Host and Path route with pattern, URL in request does not match", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{"v1": "bbb", "v2": "222"}, + host: "aaa.bbb.ccc", + path: "/111/222/333", + path_template: `/111/{v2:[0-9]{3}}/333`, + host_template: `aaa.{v1:[a-z]{3}}.ccc`, + shouldMatch: false, + }, + { + title: "Host and Path route with multiple patterns, match", + route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), + request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), + vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, + host: "aaa.bbb.ccc", + path: "/111/222/333", + path_template: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`, + host_template: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, + shouldMatch: true, + }, + { + title: "Host and Path route with multiple patterns, URL in request does not match", + route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), + request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), + vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, + host: "aaa.bbb.ccc", + path: "/111/222/333", + path_template: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`, + host_template: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`, + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestHeaders(t *testing.T) { + // newRequestHeaders creates a new request with a method, url, and headers + newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { + req, err := http.NewRequest(method, url, nil) + if err != nil { + panic(err) + } + for k, v := range headers { + req.Header.Add(k, v) + } + return req + } + + tests := []routeTest{ + { + title: "Headers route, match", + route: new(Route).Headers("foo", "bar", "baz", "ding"), + request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Headers route, bad header values", + route: new(Route).Headers("foo", "bar", "baz", "ding"), + request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Headers route, regex header values to match", + route: new(Route).Headers("foo", "ba[zr]"), + request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Headers route, regex header values to match", + route: new(Route).HeadersRegexp("foo", "ba[zr]"), + request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } + +} + +func TestMethods(t *testing.T) { + tests := []routeTest{ + { + title: "Methods route, match GET", + route: new(Route).Methods("GET", "POST"), + request: newRequest("GET", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Methods route, match POST", + route: new(Route).Methods("GET", "POST"), + request: newRequest("POST", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Methods route, bad method", + route: new(Route).Methods("GET", "POST"), + request: newRequest("PUT", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestQueries(t *testing.T) { + tests := []routeTest{ + { + title: "Queries route, match", + route: new(Route).Queries("foo", "bar", "baz", "ding"), + request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route, match with a query string", + route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), + request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), + vars: map[string]string{}, + host: "", + path: "", + path_template: `/api`, + host_template: `www.example.com`, + shouldMatch: true, + }, + { + title: "Queries route, match with a query string out of order", + route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), + request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), + vars: map[string]string{}, + host: "", + path: "", + path_template: `/api`, + host_template: `www.example.com`, + shouldMatch: true, + }, + { + title: "Queries route, bad query", + route: new(Route).Queries("foo", "bar", "baz", "ding"), + request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with pattern, match", + route: new(Route).Queries("foo", "{v1}"), + request: newRequest("GET", "http://localhost?foo=bar"), + vars: map[string]string{"v1": "bar"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with multiple patterns, match", + route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), + request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), + vars: map[string]string{"v1": "bar", "v2": "ding"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with regexp pattern, match", + route: new(Route).Queries("foo", "{v1:[0-9]+}"), + request: newRequest("GET", "http://localhost?foo=10"), + vars: map[string]string{"v1": "10"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with regexp pattern, regexp does not match", + route: new(Route).Queries("foo", "{v1:[0-9]+}"), + request: newRequest("GET", "http://localhost?foo=a"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with regexp pattern with quantifier, match", + route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), + request: newRequest("GET", "http://localhost?foo=1"), + vars: map[string]string{"v1": "1"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with regexp pattern with quantifier, additional variable in query string, match", + route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), + request: newRequest("GET", "http://localhost?bar=2&foo=1"), + vars: map[string]string{"v1": "1"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with regexp pattern with quantifier, regexp does not match", + route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), + request: newRequest("GET", "http://localhost?foo=12"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with regexp pattern with quantifier, additional capturing group", + route: new(Route).Queries("foo", "{v1:[0-9]{1}(a|b)}"), + request: newRequest("GET", "http://localhost?foo=1a"), + vars: map[string]string{"v1": "1a"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match", + route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), + request: newRequest("GET", "http://localhost?foo=12"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with hyphenated name, match", + route: new(Route).Queries("foo", "{v-1}"), + request: newRequest("GET", "http://localhost?foo=bar"), + vars: map[string]string{"v-1": "bar"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with multiple hyphenated names, match", + route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"), + request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), + vars: map[string]string{"v-1": "bar", "v-2": "ding"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with hyphenate name and pattern, match", + route: new(Route).Queries("foo", "{v-1:[0-9]+}"), + request: newRequest("GET", "http://localhost?foo=10"), + vars: map[string]string{"v-1": "10"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group", + route: new(Route).Queries("foo", "{v-1:[0-9]{1}(a|b)}"), + request: newRequest("GET", "http://localhost?foo=1a"), + vars: map[string]string{"v-1": "1a"}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with empty value, should match", + route: new(Route).Queries("foo", ""), + request: newRequest("GET", "http://localhost?foo=bar"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with empty value and no parameter in request, should not match", + route: new(Route).Queries("foo", ""), + request: newRequest("GET", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with empty value and empty parameter in request, should match", + route: new(Route).Queries("foo", ""), + request: newRequest("GET", "http://localhost?foo="), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route with overlapping value, should not match", + route: new(Route).Queries("foo", "bar"), + request: newRequest("GET", "http://localhost?foo=barfoo"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with no parameter in request, should not match", + route: new(Route).Queries("foo", "{bar}"), + request: newRequest("GET", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + { + title: "Queries route with empty parameter in request, should match", + route: new(Route).Queries("foo", "{bar}"), + request: newRequest("GET", "http://localhost?foo="), + vars: map[string]string{"foo": ""}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Queries route, bad submatch", + route: new(Route).Queries("foo", "bar", "baz", "ding"), + request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestSchemes(t *testing.T) { + tests := []routeTest{ + // Schemes + { + title: "Schemes route, match https", + route: new(Route).Schemes("https", "ftp"), + request: newRequest("GET", "https://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Schemes route, match ftp", + route: new(Route).Schemes("https", "ftp"), + request: newRequest("GET", "ftp://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "Schemes route, bad scheme", + route: new(Route).Schemes("https", "ftp"), + request: newRequest("GET", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + } + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestMatcherFunc(t *testing.T) { + m := func(r *http.Request, m *RouteMatch) bool { + if r.URL.Host == "aaa.bbb.ccc" { + return true + } + return false + } + + tests := []routeTest{ + { + title: "MatchFunc route, match", + route: new(Route).MatcherFunc(m), + request: newRequest("GET", "http://aaa.bbb.ccc"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: true, + }, + { + title: "MatchFunc route, non-match", + route: new(Route).MatcherFunc(m), + request: newRequest("GET", "http://aaa.222.ccc"), + vars: map[string]string{}, + host: "", + path: "", + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestBuildVarsFunc(t *testing.T) { + tests := []routeTest{ + { + title: "BuildVarsFunc set on route", + route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { + vars["v1"] = "3" + vars["v2"] = "a" + return vars + }), + request: newRequest("GET", "http://localhost/111/2"), + path: "/111/3a", + path_template: `/111/{v1:\d}{v2:.*}`, + shouldMatch: true, + }, + { + title: "BuildVarsFunc set on route and parent route", + route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { + vars["v1"] = "2" + return vars + }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { + vars["v2"] = "b" + return vars + }), + request: newRequest("GET", "http://localhost/1/a"), + path: "/2/b", + path_template: `/{v1:\d}/{v2:\w}`, + shouldMatch: true, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestSubRouter(t *testing.T) { + subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() + subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() + + tests := []routeTest{ + { + route: subrouter1.Path("/{v2:[a-z]+}"), + request: newRequest("GET", "http://aaa.google.com/bbb"), + vars: map[string]string{"v1": "aaa", "v2": "bbb"}, + host: "aaa.google.com", + path: "/bbb", + path_template: `/{v2:[a-z]+}`, + host_template: `{v1:[a-z]+}.google.com`, + shouldMatch: true, + }, + { + route: subrouter1.Path("/{v2:[a-z]+}"), + request: newRequest("GET", "http://111.google.com/111"), + vars: map[string]string{"v1": "aaa", "v2": "bbb"}, + host: "aaa.google.com", + path: "/bbb", + path_template: `/{v2:[a-z]+}`, + host_template: `{v1:[a-z]+}.google.com`, + shouldMatch: false, + }, + { + route: subrouter2.Path("/baz/{v2}"), + request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), + vars: map[string]string{"v1": "bar", "v2": "ding"}, + host: "", + path: "/foo/bar/baz/ding", + path_template: `/foo/{v1}/baz/{v2}`, + shouldMatch: true, + }, + { + route: subrouter2.Path("/baz/{v2}"), + request: newRequest("GET", "http://localhost/foo/bar"), + vars: map[string]string{"v1": "bar", "v2": "ding"}, + host: "", + path: "/foo/bar/baz/ding", + path_template: `/foo/{v1}/baz/{v2}`, + shouldMatch: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestNamedRoutes(t *testing.T) { + r1 := NewRouter() + r1.NewRoute().Name("a") + r1.NewRoute().Name("b") + r1.NewRoute().Name("c") + + r2 := r1.NewRoute().Subrouter() + r2.NewRoute().Name("d") + r2.NewRoute().Name("e") + r2.NewRoute().Name("f") + + r3 := r2.NewRoute().Subrouter() + r3.NewRoute().Name("g") + r3.NewRoute().Name("h") + r3.NewRoute().Name("i") + + if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { + t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) + } else if r1.Get("i") == nil { + t.Errorf("Subroute name not registered") + } +} + +func TestStrictSlash(t *testing.T) { + r := NewRouter() + r.StrictSlash(true) + + tests := []routeTest{ + { + title: "Redirect path without slash", + route: r.NewRoute().Path("/111/"), + request: newRequest("GET", "http://localhost/111"), + vars: map[string]string{}, + host: "", + path: "/111/", + shouldMatch: true, + shouldRedirect: true, + }, + { + title: "Do not redirect path with slash", + route: r.NewRoute().Path("/111/"), + request: newRequest("GET", "http://localhost/111/"), + vars: map[string]string{}, + host: "", + path: "/111/", + shouldMatch: true, + shouldRedirect: false, + }, + { + title: "Redirect path with slash", + route: r.NewRoute().Path("/111"), + request: newRequest("GET", "http://localhost/111/"), + vars: map[string]string{}, + host: "", + path: "/111", + shouldMatch: true, + shouldRedirect: true, + }, + { + title: "Do not redirect path without slash", + route: r.NewRoute().Path("/111"), + request: newRequest("GET", "http://localhost/111"), + vars: map[string]string{}, + host: "", + path: "/111", + shouldMatch: true, + shouldRedirect: false, + }, + { + title: "Propagate StrictSlash to subrouters", + route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), + request: newRequest("GET", "http://localhost/static/images"), + vars: map[string]string{}, + host: "", + path: "/static/images/", + shouldMatch: true, + shouldRedirect: true, + }, + { + title: "Ignore StrictSlash for path prefix", + route: r.NewRoute().PathPrefix("/static/"), + request: newRequest("GET", "http://localhost/static/logo.png"), + vars: map[string]string{}, + host: "", + path: "/static/", + shouldMatch: true, + shouldRedirect: false, + }, + } + + for _, test := range tests { + testRoute(t, test) + testTemplate(t, test) + } +} + +func TestWalkSingleDepth(t *testing.T) { + r0 := NewRouter() + r1 := NewRouter() + r2 := NewRouter() + + r0.Path("/g") + r0.Path("/o") + r0.Path("/d").Handler(r1) + r0.Path("/r").Handler(r2) + r0.Path("/a") + + r1.Path("/z") + r1.Path("/i") + r1.Path("/l") + r1.Path("/l") + + r2.Path("/i") + r2.Path("/l") + r2.Path("/l") + + paths := []string{"g", "o", "r", "i", "l", "l", "a"} + depths := []int{0, 0, 0, 1, 1, 1, 0} + i := 0 + err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error { + matcher := route.matchers[0].(*routeRegexp) + if matcher.template == "/d" { + return SkipRouter + } + if len(ancestors) != depths[i] { + t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors)) + } + if matcher.template != "/"+paths[i] { + t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template) + } + i++ + return nil + }) + if err != nil { + panic(err) + } + if i != len(paths) { + t.Errorf("Expected %d routes, found %d", len(paths), i) + } +} + +func TestWalkNested(t *testing.T) { + router := NewRouter() + + g := router.Path("/g").Subrouter() + o := g.PathPrefix("/o").Subrouter() + r := o.PathPrefix("/r").Subrouter() + i := r.PathPrefix("/i").Subrouter() + l1 := i.PathPrefix("/l").Subrouter() + l2 := l1.PathPrefix("/l").Subrouter() + l2.Path("/a") + + paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"} + idx := 0 + err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { + path := paths[idx] + tpl := route.regexp.path.template + if tpl != path { + t.Errorf(`Expected %s got %s`, path, tpl) + } + idx++ + return nil + }) + if err != nil { + panic(err) + } + if idx != len(paths) { + t.Errorf("Expected %d routes, found %d", len(paths), idx) + } +} + +func TestSubrouterErrorHandling(t *testing.T) { + superRouterCalled := false + subRouterCalled := false + + router := NewRouter() + router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + superRouterCalled = true + }) + subRouter := router.PathPrefix("/bign8").Subrouter() + subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + subRouterCalled = true + }) + + req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil) + router.ServeHTTP(NewRecorder(), req) + + if superRouterCalled { + t.Error("Super router 404 handler called when sub-router 404 handler is available.") + } + if !subRouterCalled { + t.Error("Sub-router 404 handler was not called.") + } +} + +// ---------------------------------------------------------------------------- +// Helpers +// ---------------------------------------------------------------------------- + +func getRouteTemplate(route *Route) string { + host, err := route.GetHostTemplate() + if err != nil { + host = "none" + } + path, err := route.GetPathTemplate() + if err != nil { + path = "none" + } + return fmt.Sprintf("Host: %v, Path: %v", host, path) +} + +func testRoute(t *testing.T, test routeTest) { + request := test.request + route := test.route + vars := test.vars + shouldMatch := test.shouldMatch + host := test.host + path := test.path + url := test.host + test.path + shouldRedirect := test.shouldRedirect + + var match RouteMatch + ok := route.Match(request, &match) + if ok != shouldMatch { + msg := "Should match" + if !shouldMatch { + msg = "Should not match" + } + t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) + return + } + if shouldMatch { + if test.vars != nil && !stringMapEqual(test.vars, match.Vars) { + t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) + return + } + if host != "" { + u, _ := test.route.URLHost(mapToPairs(match.Vars)...) + if host != u.Host { + t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route)) + return + } + } + if path != "" { + u, _ := route.URLPath(mapToPairs(match.Vars)...) + if path != u.Path { + t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route)) + return + } + } + if url != "" { + u, _ := route.URL(mapToPairs(match.Vars)...) + if url != u.Host+u.Path { + t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route)) + return + } + } + if shouldRedirect && match.Handler == nil { + t.Errorf("(%v) Did not redirect", test.title) + return + } + if !shouldRedirect && match.Handler != nil { + t.Errorf("(%v) Unexpected redirect", test.title) + return + } + } +} + +func testTemplate(t *testing.T, test routeTest) { + route := test.route + path_template := test.path_template + if len(path_template) == 0 { + path_template = test.path + } + host_template := test.host_template + if len(host_template) == 0 { + host_template = test.host + } + + path_tmpl, path_err := route.GetPathTemplate() + if path_err == nil && path_tmpl != path_template { + t.Errorf("(%v) GetPathTemplate not equal: expected %v, got %v", test.title, path_template, path_tmpl) + } + + host_tmpl, host_err := route.GetHostTemplate() + if host_err == nil && host_tmpl != host_template { + t.Errorf("(%v) GetHostTemplate not equal: expected %v, got %v", test.title, host_template, host_tmpl) + } +} + +// Tests that the context is cleared or not cleared properly depending on +// the configuration of the router +func TestKeepContext(t *testing.T) { + func1 := func(w http.ResponseWriter, r *http.Request) {} + + r := NewRouter() + r.HandleFunc("/", func1).Name("func1") + + req, _ := http.NewRequest("GET", "http://localhost/", nil) + context.Set(req, "t", 1) + + res := new(http.ResponseWriter) + r.ServeHTTP(*res, req) + + if _, ok := context.GetOk(req, "t"); ok { + t.Error("Context should have been cleared at end of request") + } + + r.KeepContext = true + + req, _ = http.NewRequest("GET", "http://localhost/", nil) + context.Set(req, "t", 1) + + r.ServeHTTP(*res, req) + if _, ok := context.GetOk(req, "t"); !ok { + t.Error("Context should NOT have been cleared at end of request") + } + +} + +type TestA301ResponseWriter struct { + hh http.Header + status int +} + +func (ho TestA301ResponseWriter) Header() http.Header { + return http.Header(ho.hh) +} + +func (ho TestA301ResponseWriter) Write(b []byte) (int, error) { + return 0, nil +} + +func (ho TestA301ResponseWriter) WriteHeader(code int) { + ho.status = code +} + +func Test301Redirect(t *testing.T) { + m := make(http.Header) + + func1 := func(w http.ResponseWriter, r *http.Request) {} + func2 := func(w http.ResponseWriter, r *http.Request) {} + + r := NewRouter() + r.HandleFunc("/api/", func2).Name("func2") + r.HandleFunc("/", func1).Name("func1") + + req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) + + res := TestA301ResponseWriter{ + hh: m, + status: 0, + } + r.ServeHTTP(&res, req) + + if "http://localhost/api/?abc=def" != res.hh["Location"][0] { + t.Errorf("Should have complete URL with query string") + } +} + +func TestSkipClean(t *testing.T) { + func1 := func(w http.ResponseWriter, r *http.Request) {} + func2 := func(w http.ResponseWriter, r *http.Request) {} + + r := NewRouter() + r.SkipClean(true) + r.HandleFunc("/api/", func2).Name("func2") + r.HandleFunc("/", func1).Name("func1") + + req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) + res := NewRecorder() + r.ServeHTTP(res, req) + + if len(res.HeaderMap["Location"]) != 0 { + t.Errorf("Shouldn't redirect since skip clean is disabled") + } +} + +// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW +func TestSubrouterHeader(t *testing.T) { + expected := "func1 response" + func1 := func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, expected) + } + func2 := func(http.ResponseWriter, *http.Request) {} + + r := NewRouter() + s := r.Headers("SomeSpecialHeader", "").Subrouter() + s.HandleFunc("/", func1).Name("func1") + r.HandleFunc("/", func2).Name("func2") + + req, _ := http.NewRequest("GET", "http://localhost/", nil) + req.Header.Add("SomeSpecialHeader", "foo") + match := new(RouteMatch) + matched := r.Match(req, match) + if !matched { + t.Errorf("Should match request") + } + if match.Route.GetName() != "func1" { + t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) + } + resp := NewRecorder() + match.Handler.ServeHTTP(resp, req) + if resp.Body.String() != expected { + t.Errorf("Expecting %q", expected) + } +} + +// mapToPairs converts a string map to a slice of string pairs +func mapToPairs(m map[string]string) []string { + var i int + p := make([]string, len(m)*2) + for k, v := range m { + p[i] = k + p[i+1] = v + i += 2 + } + return p +} + +// stringMapEqual checks the equality of two string maps +func stringMapEqual(m1, m2 map[string]string) bool { + nil1 := m1 == nil + nil2 := m2 == nil + if nil1 != nil2 || len(m1) != len(m2) { + return false + } + for k, v := range m1 { + if v != m2[k] { + return false + } + } + return true +} + +// newRequest is a helper function to create a new request with a method and url +func newRequest(method, url string) *http.Request { + req, err := http.NewRequest(method, url, nil) + if err != nil { + panic(err) + } + return req +} diff --git a/vendor/github.com/gorilla/mux/old_test.go b/vendor/github.com/gorilla/mux/old_test.go new file mode 100644 index 0000000000..c385a25191 --- /dev/null +++ b/vendor/github.com/gorilla/mux/old_test.go @@ -0,0 +1,710 @@ +// Old tests ported to Go1. This is a mess. Want to drop it one day. + +// Copyright 2011 Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "bytes" + "net/http" + "testing" +) + +// ---------------------------------------------------------------------------- +// ResponseRecorder +// ---------------------------------------------------------------------------- +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// ResponseRecorder is an implementation of http.ResponseWriter that +// records its mutations for later inspection in tests. +type ResponseRecorder struct { + Code int // the HTTP response code from WriteHeader + HeaderMap http.Header // the HTTP response headers + Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to + Flushed bool +} + +// NewRecorder returns an initialized ResponseRecorder. +func NewRecorder() *ResponseRecorder { + return &ResponseRecorder{ + HeaderMap: make(http.Header), + Body: new(bytes.Buffer), + } +} + +// Header returns the response headers. +func (rw *ResponseRecorder) Header() http.Header { + return rw.HeaderMap +} + +// Write always succeeds and writes to rw.Body, if not nil. +func (rw *ResponseRecorder) Write(buf []byte) (int, error) { + if rw.Body != nil { + rw.Body.Write(buf) + } + if rw.Code == 0 { + rw.Code = http.StatusOK + } + return len(buf), nil +} + +// WriteHeader sets rw.Code. +func (rw *ResponseRecorder) WriteHeader(code int) { + rw.Code = code +} + +// Flush sets rw.Flushed to true. +func (rw *ResponseRecorder) Flush() { + rw.Flushed = true +} + +// ---------------------------------------------------------------------------- + +func TestRouteMatchers(t *testing.T) { + var scheme, host, path, query, method string + var headers map[string]string + var resultVars map[bool]map[string]string + + router := NewRouter() + router.NewRoute().Host("{var1}.google.com"). + Path("/{var2:[a-z]+}/{var3:[0-9]+}"). + Queries("foo", "bar"). + Methods("GET"). + Schemes("https"). + Headers("x-requested-with", "XMLHttpRequest") + router.NewRoute().Host("www.{var4}.com"). + PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). + Queries("baz", "ding"). + Methods("POST"). + Schemes("http"). + Headers("Content-Type", "application/json") + + reset := func() { + // Everything match. + scheme = "https" + host = "www.google.com" + path = "/product/42" + query = "?foo=bar" + method = "GET" + headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} + resultVars = map[bool]map[string]string{ + true: {"var1": "www", "var2": "product", "var3": "42"}, + false: {}, + } + } + + reset2 := func() { + // Everything match. + scheme = "http" + host = "www.google.com" + path = "/foo/product/42/path/that/is/ignored" + query = "?baz=ding" + method = "POST" + headers = map[string]string{"Content-Type": "application/json"} + resultVars = map[bool]map[string]string{ + true: {"var4": "google", "var5": "product", "var6": "42"}, + false: {}, + } + } + + match := func(shouldMatch bool) { + url := scheme + "://" + host + path + query + request, _ := http.NewRequest(method, url, nil) + for key, value := range headers { + request.Header.Add(key, value) + } + + var routeMatch RouteMatch + matched := router.Match(request, &routeMatch) + if matched != shouldMatch { + // Need better messages. :) + if matched { + t.Errorf("Should match.") + } else { + t.Errorf("Should not match.") + } + } + + if matched { + currentRoute := routeMatch.Route + if currentRoute == nil { + t.Errorf("Expected a current route.") + } + vars := routeMatch.Vars + expectedVars := resultVars[shouldMatch] + if len(vars) != len(expectedVars) { + t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) + } + for name, value := range vars { + if expectedVars[name] != value { + t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) + } + } + } + } + + // 1st route -------------------------------------------------------------- + + // Everything match. + reset() + match(true) + + // Scheme doesn't match. + reset() + scheme = "http" + match(false) + + // Host doesn't match. + reset() + host = "www.mygoogle.com" + match(false) + + // Path doesn't match. + reset() + path = "/product/notdigits" + match(false) + + // Query doesn't match. + reset() + query = "?foo=baz" + match(false) + + // Method doesn't match. + reset() + method = "POST" + match(false) + + // Header doesn't match. + reset() + headers = map[string]string{} + match(false) + + // Everything match, again. + reset() + match(true) + + // 2nd route -------------------------------------------------------------- + + // Everything match. + reset2() + match(true) + + // Scheme doesn't match. + reset2() + scheme = "https" + match(false) + + // Host doesn't match. + reset2() + host = "sub.google.com" + match(false) + + // Path doesn't match. + reset2() + path = "/bar/product/42" + match(false) + + // Query doesn't match. + reset2() + query = "?foo=baz" + match(false) + + // Method doesn't match. + reset2() + method = "GET" + match(false) + + // Header doesn't match. + reset2() + headers = map[string]string{} + match(false) + + // Everything match, again. + reset2() + match(true) +} + +type headerMatcherTest struct { + matcher headerMatcher + headers map[string]string + result bool +} + +var headerMatcherTests = []headerMatcherTest{ + { + matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), + headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, + result: true, + }, + { + matcher: headerMatcher(map[string]string{"x-requested-with": ""}), + headers: map[string]string{"X-Requested-With": "anything"}, + result: true, + }, + { + matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), + headers: map[string]string{}, + result: false, + }, +} + +type hostMatcherTest struct { + matcher *Route + url string + vars map[string]string + result bool +} + +var hostMatcherTests = []hostMatcherTest{ + { + matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), + url: "http://abc.def.ghi/", + vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, + result: true, + }, + { + matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), + url: "http://a.b.c/", + vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, + result: false, + }, +} + +type methodMatcherTest struct { + matcher methodMatcher + method string + result bool +} + +var methodMatcherTests = []methodMatcherTest{ + { + matcher: methodMatcher([]string{"GET", "POST", "PUT"}), + method: "GET", + result: true, + }, + { + matcher: methodMatcher([]string{"GET", "POST", "PUT"}), + method: "POST", + result: true, + }, + { + matcher: methodMatcher([]string{"GET", "POST", "PUT"}), + method: "PUT", + result: true, + }, + { + matcher: methodMatcher([]string{"GET", "POST", "PUT"}), + method: "DELETE", + result: false, + }, +} + +type pathMatcherTest struct { + matcher *Route + url string + vars map[string]string + result bool +} + +var pathMatcherTests = []pathMatcherTest{ + { + matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), + url: "http://localhost:8080/123/456/789", + vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, + result: true, + }, + { + matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), + url: "http://localhost:8080/1/2/3", + vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, + result: false, + }, +} + +type schemeMatcherTest struct { + matcher schemeMatcher + url string + result bool +} + +var schemeMatcherTests = []schemeMatcherTest{ + { + matcher: schemeMatcher([]string{"http", "https"}), + url: "http://localhost:8080/", + result: true, + }, + { + matcher: schemeMatcher([]string{"http", "https"}), + url: "https://localhost:8080/", + result: true, + }, + { + matcher: schemeMatcher([]string{"https"}), + url: "http://localhost:8080/", + result: false, + }, + { + matcher: schemeMatcher([]string{"http"}), + url: "https://localhost:8080/", + result: false, + }, +} + +type urlBuildingTest struct { + route *Route + vars []string + url string +} + +var urlBuildingTests = []urlBuildingTest{ + { + route: new(Route).Host("foo.domain.com"), + vars: []string{}, + url: "http://foo.domain.com", + }, + { + route: new(Route).Host("{subdomain}.domain.com"), + vars: []string{"subdomain", "bar"}, + url: "http://bar.domain.com", + }, + { + route: new(Route).Host("foo.domain.com").Path("/articles"), + vars: []string{}, + url: "http://foo.domain.com/articles", + }, + { + route: new(Route).Path("/articles"), + vars: []string{}, + url: "/articles", + }, + { + route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), + vars: []string{"category", "technology", "id", "42"}, + url: "/articles/technology/42", + }, + { + route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), + vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, + url: "http://foo.domain.com/articles/technology/42", + }, +} + +func TestHeaderMatcher(t *testing.T) { + for _, v := range headerMatcherTests { + request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + for key, value := range v.headers { + request.Header.Add(key, value) + } + var routeMatch RouteMatch + result := v.matcher.Match(request, &routeMatch) + if result != v.result { + if v.result { + t.Errorf("%#v: should match %v.", v.matcher, request.Header) + } else { + t.Errorf("%#v: should not match %v.", v.matcher, request.Header) + } + } + } +} + +func TestHostMatcher(t *testing.T) { + for _, v := range hostMatcherTests { + request, _ := http.NewRequest("GET", v.url, nil) + var routeMatch RouteMatch + result := v.matcher.Match(request, &routeMatch) + vars := routeMatch.Vars + if result != v.result { + if v.result { + t.Errorf("%#v: should match %v.", v.matcher, v.url) + } else { + t.Errorf("%#v: should not match %v.", v.matcher, v.url) + } + } + if result { + if len(vars) != len(v.vars) { + t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) + } + for name, value := range vars { + if v.vars[name] != value { + t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) + } + } + } else { + if len(vars) != 0 { + t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) + } + } + } +} + +func TestMethodMatcher(t *testing.T) { + for _, v := range methodMatcherTests { + request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) + var routeMatch RouteMatch + result := v.matcher.Match(request, &routeMatch) + if result != v.result { + if v.result { + t.Errorf("%#v: should match %v.", v.matcher, v.method) + } else { + t.Errorf("%#v: should not match %v.", v.matcher, v.method) + } + } + } +} + +func TestPathMatcher(t *testing.T) { + for _, v := range pathMatcherTests { + request, _ := http.NewRequest("GET", v.url, nil) + var routeMatch RouteMatch + result := v.matcher.Match(request, &routeMatch) + vars := routeMatch.Vars + if result != v.result { + if v.result { + t.Errorf("%#v: should match %v.", v.matcher, v.url) + } else { + t.Errorf("%#v: should not match %v.", v.matcher, v.url) + } + } + if result { + if len(vars) != len(v.vars) { + t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) + } + for name, value := range vars { + if v.vars[name] != value { + t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) + } + } + } else { + if len(vars) != 0 { + t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) + } + } + } +} + +func TestSchemeMatcher(t *testing.T) { + for _, v := range schemeMatcherTests { + request, _ := http.NewRequest("GET", v.url, nil) + var routeMatch RouteMatch + result := v.matcher.Match(request, &routeMatch) + if result != v.result { + if v.result { + t.Errorf("%#v: should match %v.", v.matcher, v.url) + } else { + t.Errorf("%#v: should not match %v.", v.matcher, v.url) + } + } + } +} + +func TestUrlBuilding(t *testing.T) { + + for _, v := range urlBuildingTests { + u, _ := v.route.URL(v.vars...) + url := u.String() + if url != v.url { + t.Errorf("expected %v, got %v", v.url, url) + /* + reversePath := "" + reverseHost := "" + if v.route.pathTemplate != nil { + reversePath = v.route.pathTemplate.Reverse + } + if v.route.hostTemplate != nil { + reverseHost = v.route.hostTemplate.Reverse + } + + t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) + */ + } + } + + ArticleHandler := func(w http.ResponseWriter, r *http.Request) { + } + + router := NewRouter() + router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") + + url, _ := router.Get("article").URL("category", "technology", "id", "42") + expected := "/articles/technology/42" + if url.String() != expected { + t.Errorf("Expected %v, got %v", expected, url.String()) + } +} + +func TestMatchedRouteName(t *testing.T) { + routeName := "stock" + router := NewRouter() + route := router.NewRoute().Path("/products/").Name(routeName) + + url := "http://www.example.com/products/" + request, _ := http.NewRequest("GET", url, nil) + var rv RouteMatch + ok := router.Match(request, &rv) + + if !ok || rv.Route != route { + t.Errorf("Expected same route, got %+v.", rv.Route) + } + + retName := rv.Route.GetName() + if retName != routeName { + t.Errorf("Expected %q, got %q.", routeName, retName) + } +} + +func TestSubRouting(t *testing.T) { + // Example from docs. + router := NewRouter() + subrouter := router.NewRoute().Host("www.example.com").Subrouter() + route := subrouter.NewRoute().Path("/products/").Name("products") + + url := "http://www.example.com/products/" + request, _ := http.NewRequest("GET", url, nil) + var rv RouteMatch + ok := router.Match(request, &rv) + + if !ok || rv.Route != route { + t.Errorf("Expected same route, got %+v.", rv.Route) + } + + u, _ := router.Get("products").URL() + builtURL := u.String() + // Yay, subroute aware of the domain when building! + if builtURL != url { + t.Errorf("Expected %q, got %q.", url, builtURL) + } +} + +func TestVariableNames(t *testing.T) { + route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") + if route.err == nil { + t.Errorf("Expected error for duplicated variable names") + } +} + +func TestRedirectSlash(t *testing.T) { + var route *Route + var routeMatch RouteMatch + r := NewRouter() + + r.StrictSlash(false) + route = r.NewRoute() + if route.strictSlash != false { + t.Errorf("Expected false redirectSlash.") + } + + r.StrictSlash(true) + route = r.NewRoute() + if route.strictSlash != true { + t.Errorf("Expected true redirectSlash.") + } + + route = new(Route) + route.strictSlash = true + route.Path("/{arg1}/{arg2:[0-9]+}/") + request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) + routeMatch = RouteMatch{} + _ = route.Match(request, &routeMatch) + vars := routeMatch.Vars + if vars["arg1"] != "foo" { + t.Errorf("Expected foo.") + } + if vars["arg2"] != "123" { + t.Errorf("Expected 123.") + } + rsp := NewRecorder() + routeMatch.Handler.ServeHTTP(rsp, request) + if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { + t.Errorf("Expected redirect header.") + } + + route = new(Route) + route.strictSlash = true + route.Path("/{arg1}/{arg2:[0-9]+}") + request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) + routeMatch = RouteMatch{} + _ = route.Match(request, &routeMatch) + vars = routeMatch.Vars + if vars["arg1"] != "foo" { + t.Errorf("Expected foo.") + } + if vars["arg2"] != "123" { + t.Errorf("Expected 123.") + } + rsp = NewRecorder() + routeMatch.Handler.ServeHTTP(rsp, request) + if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { + t.Errorf("Expected redirect header.") + } +} + +// Test for the new regexp library, still not available in stable Go. +func TestNewRegexp(t *testing.T) { + var p *routeRegexp + var matches []string + + tests := map[string]map[string][]string{ + "/{foo:a{2}}": { + "/a": nil, + "/aa": {"aa"}, + "/aaa": nil, + "/aaaa": nil, + }, + "/{foo:a{2,}}": { + "/a": nil, + "/aa": {"aa"}, + "/aaa": {"aaa"}, + "/aaaa": {"aaaa"}, + }, + "/{foo:a{2,3}}": { + "/a": nil, + "/aa": {"aa"}, + "/aaa": {"aaa"}, + "/aaaa": nil, + }, + "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { + "/a": nil, + "/ab": nil, + "/abc": nil, + "/abcd": nil, + "/abc/ab": {"abc", "ab"}, + "/abc/abc": nil, + "/abcd/ab": nil, + }, + `/{foo:\w{3,}}/{bar:\d{2,}}`: { + "/a": nil, + "/ab": nil, + "/abc": nil, + "/abc/1": nil, + "/abc/12": {"abc", "12"}, + "/abcd/12": {"abcd", "12"}, + "/abcd/123": {"abcd", "123"}, + }, + } + + for pattern, paths := range tests { + p, _ = newRouteRegexp(pattern, false, false, false, false) + for path, result := range paths { + matches = p.regexp.FindStringSubmatch(path) + if result == nil { + if matches != nil { + t.Errorf("%v should not match %v.", pattern, path) + } + } else { + if len(matches) != len(result)+1 { + t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) + } else { + for k, v := range result { + if matches[k+1] != v { + t.Errorf("Expected %v, got %v.", v, matches[k+1]) + } + } + } + } + } + } +} diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go new file mode 100644 index 0000000000..08710bc984 --- /dev/null +++ b/vendor/github.com/gorilla/mux/regexp.go @@ -0,0 +1,312 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "bytes" + "fmt" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" +) + +// newRouteRegexp parses a route template and returns a routeRegexp, +// used to match a host, a path or a query string. +// +// It will extract named variables, assemble a regexp to be matched, create +// a "reverse" template to build URLs and compile regexps to validate variable +// values used in URL building. +// +// Previously we accepted only Python-like identifiers for variable +// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that +// name and pattern can't be empty, and names can't contain a colon. +func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) { + // Check if it is well-formed. + idxs, errBraces := braceIndices(tpl) + if errBraces != nil { + return nil, errBraces + } + // Backup the original. + template := tpl + // Now let's parse it. + defaultPattern := "[^/]+" + if matchQuery { + defaultPattern = "[^?&]*" + } else if matchHost { + defaultPattern = "[^.]+" + matchPrefix = false + } + // Only match strict slash if not matching + if matchPrefix || matchHost || matchQuery { + strictSlash = false + } + // Set a flag for strictSlash. + endSlash := false + if strictSlash && strings.HasSuffix(tpl, "/") { + tpl = tpl[:len(tpl)-1] + endSlash = true + } + varsN := make([]string, len(idxs)/2) + varsR := make([]*regexp.Regexp, len(idxs)/2) + pattern := bytes.NewBufferString("") + pattern.WriteByte('^') + reverse := bytes.NewBufferString("") + var end int + var err error + for i := 0; i < len(idxs); i += 2 { + // Set all values we are interested in. + raw := tpl[end:idxs[i]] + end = idxs[i+1] + parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) + name := parts[0] + patt := defaultPattern + if len(parts) == 2 { + patt = parts[1] + } + // Name or pattern can't be empty. + if name == "" || patt == "" { + return nil, fmt.Errorf("mux: missing name or pattern in %q", + tpl[idxs[i]:end]) + } + // Build the regexp pattern. + fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) + + // Build the reverse template. + fmt.Fprintf(reverse, "%s%%s", raw) + + // Append variable name and compiled pattern. + varsN[i/2] = name + varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) + if err != nil { + return nil, err + } + } + // Add the remaining. + raw := tpl[end:] + pattern.WriteString(regexp.QuoteMeta(raw)) + if strictSlash { + pattern.WriteString("[/]?") + } + if matchQuery { + // Add the default pattern if the query value is empty + if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { + pattern.WriteString(defaultPattern) + } + } + if !matchPrefix { + pattern.WriteByte('$') + } + reverse.WriteString(raw) + if endSlash { + reverse.WriteByte('/') + } + // Compile full regexp. + reg, errCompile := regexp.Compile(pattern.String()) + if errCompile != nil { + return nil, errCompile + } + // Done! + return &routeRegexp{ + template: template, + matchHost: matchHost, + matchQuery: matchQuery, + strictSlash: strictSlash, + regexp: reg, + reverse: reverse.String(), + varsN: varsN, + varsR: varsR, + }, nil +} + +// routeRegexp stores a regexp to match a host or path and information to +// collect and validate route variables. +type routeRegexp struct { + // The unmodified template. + template string + // True for host match, false for path or query string match. + matchHost bool + // True for query string match, false for path and host match. + matchQuery bool + // The strictSlash value defined on the route, but disabled if PathPrefix was used. + strictSlash bool + // Expanded regexp. + regexp *regexp.Regexp + // Reverse template. + reverse string + // Variable names. + varsN []string + // Variable regexps (validators). + varsR []*regexp.Regexp +} + +// Match matches the regexp against the URL host or path. +func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { + if !r.matchHost { + if r.matchQuery { + return r.matchQueryString(req) + } + + return r.regexp.MatchString(req.URL.Path) + } + + return r.regexp.MatchString(getHost(req)) +} + +// url builds a URL part using the given values. +func (r *routeRegexp) url(values map[string]string) (string, error) { + urlValues := make([]interface{}, len(r.varsN)) + for k, v := range r.varsN { + value, ok := values[v] + if !ok { + return "", fmt.Errorf("mux: missing route variable %q", v) + } + urlValues[k] = value + } + rv := fmt.Sprintf(r.reverse, urlValues...) + if !r.regexp.MatchString(rv) { + // The URL is checked against the full regexp, instead of checking + // individual variables. This is faster but to provide a good error + // message, we check individual regexps if the URL doesn't match. + for k, v := range r.varsN { + if !r.varsR[k].MatchString(values[v]) { + return "", fmt.Errorf( + "mux: variable %q doesn't match, expected %q", values[v], + r.varsR[k].String()) + } + } + } + return rv, nil +} + +// getURLQuery returns a single query parameter from a request URL. +// For a URL with foo=bar&baz=ding, we return only the relevant key +// value pair for the routeRegexp. +func (r *routeRegexp) getURLQuery(req *http.Request) string { + if !r.matchQuery { + return "" + } + templateKey := strings.SplitN(r.template, "=", 2)[0] + for key, vals := range req.URL.Query() { + if key == templateKey && len(vals) > 0 { + return key + "=" + vals[0] + } + } + return "" +} + +func (r *routeRegexp) matchQueryString(req *http.Request) bool { + return r.regexp.MatchString(r.getURLQuery(req)) +} + +// braceIndices returns the first level curly brace indices from a string. +// It returns an error in case of unbalanced braces. +func braceIndices(s string) ([]int, error) { + var level, idx int + var idxs []int + for i := 0; i < len(s); i++ { + switch s[i] { + case '{': + if level++; level == 1 { + idx = i + } + case '}': + if level--; level == 0 { + idxs = append(idxs, idx, i+1) + } else if level < 0 { + return nil, fmt.Errorf("mux: unbalanced braces in %q", s) + } + } + } + if level != 0 { + return nil, fmt.Errorf("mux: unbalanced braces in %q", s) + } + return idxs, nil +} + +// varGroupName builds a capturing group name for the indexed variable. +func varGroupName(idx int) string { + return "v" + strconv.Itoa(idx) +} + +// ---------------------------------------------------------------------------- +// routeRegexpGroup +// ---------------------------------------------------------------------------- + +// routeRegexpGroup groups the route matchers that carry variables. +type routeRegexpGroup struct { + host *routeRegexp + path *routeRegexp + queries []*routeRegexp +} + +// setMatch extracts the variables from the URL once a route matches. +func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { + // Store host variables. + if v.host != nil { + host := getHost(req) + matches := v.host.regexp.FindStringSubmatchIndex(host) + if len(matches) > 0 { + extractVars(host, matches, v.host.varsN, m.Vars) + } + } + // Store path variables. + if v.path != nil { + matches := v.path.regexp.FindStringSubmatchIndex(req.URL.Path) + if len(matches) > 0 { + extractVars(req.URL.Path, matches, v.path.varsN, m.Vars) + // Check if we should redirect. + if v.path.strictSlash { + p1 := strings.HasSuffix(req.URL.Path, "/") + p2 := strings.HasSuffix(v.path.template, "/") + if p1 != p2 { + u, _ := url.Parse(req.URL.String()) + if p1 { + u.Path = u.Path[:len(u.Path)-1] + } else { + u.Path += "/" + } + m.Handler = http.RedirectHandler(u.String(), 301) + } + } + } + } + // Store query string variables. + for _, q := range v.queries { + queryURL := q.getURLQuery(req) + matches := q.regexp.FindStringSubmatchIndex(queryURL) + if len(matches) > 0 { + extractVars(queryURL, matches, q.varsN, m.Vars) + } + } +} + +// getHost tries its best to return the request host. +func getHost(r *http.Request) string { + if r.URL.IsAbs() { + return r.URL.Host + } + host := r.Host + // Slice off any port information. + if i := strings.Index(host, ":"); i != -1 { + host = host[:i] + } + return host + +} + +func extractVars(input string, matches []int, names []string, output map[string]string) { + matchesCount := 0 + prevEnd := -1 + for i := 2; i < len(matches) && matchesCount < len(names); i += 2 { + if prevEnd < matches[i+1] { + value := input[matches[i]:matches[i+1]] + output[names[matchesCount]] = value + prevEnd = matches[i+1] + matchesCount++ + } + } +} diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go new file mode 100644 index 0000000000..6c53f9f1de --- /dev/null +++ b/vendor/github.com/gorilla/mux/route.go @@ -0,0 +1,634 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" +) + +// Route stores information to match a request and build URLs. +type Route struct { + // Parent where the route was registered (a Router). + parent parentRoute + // Request handler for the route. + handler http.Handler + // List of matchers. + matchers []matcher + // Manager for the variables from host and path. + regexp *routeRegexpGroup + // If true, when the path pattern is "/path/", accessing "/path" will + // redirect to the former and vice versa. + strictSlash bool + // If true, when the path pattern is "/path//to", accessing "/path//to" + // will not redirect + skipClean bool + // If true, this route never matches: it is only used to build URLs. + buildOnly bool + // The name used to build URLs. + name string + // Error resulted from building a route. + err error + + buildVarsFunc BuildVarsFunc +} + +func (r *Route) SkipClean() bool { + return r.skipClean +} + +// Match matches the route against the request. +func (r *Route) Match(req *http.Request, match *RouteMatch) bool { + if r.buildOnly || r.err != nil { + return false + } + // Match everything. + for _, m := range r.matchers { + if matched := m.Match(req, match); !matched { + return false + } + } + // Yay, we have a match. Let's collect some info about it. + if match.Route == nil { + match.Route = r + } + if match.Handler == nil { + match.Handler = r.handler + } + if match.Vars == nil { + match.Vars = make(map[string]string) + } + // Set variables. + if r.regexp != nil { + r.regexp.setMatch(req, match, r) + } + return true +} + +// ---------------------------------------------------------------------------- +// Route attributes +// ---------------------------------------------------------------------------- + +// GetError returns an error resulted from building the route, if any. +func (r *Route) GetError() error { + return r.err +} + +// BuildOnly sets the route to never match: it is only used to build URLs. +func (r *Route) BuildOnly() *Route { + r.buildOnly = true + return r +} + +// Handler -------------------------------------------------------------------- + +// Handler sets a handler for the route. +func (r *Route) Handler(handler http.Handler) *Route { + if r.err == nil { + r.handler = handler + } + return r +} + +// HandlerFunc sets a handler function for the route. +func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { + return r.Handler(http.HandlerFunc(f)) +} + +// GetHandler returns the handler for the route, if any. +func (r *Route) GetHandler() http.Handler { + return r.handler +} + +// Name ----------------------------------------------------------------------- + +// Name sets the name for the route, used to build URLs. +// If the name was registered already it will be overwritten. +func (r *Route) Name(name string) *Route { + if r.name != "" { + r.err = fmt.Errorf("mux: route already has name %q, can't set %q", + r.name, name) + } + if r.err == nil { + r.name = name + r.getNamedRoutes()[name] = r + } + return r +} + +// GetName returns the name for the route, if any. +func (r *Route) GetName() string { + return r.name +} + +// ---------------------------------------------------------------------------- +// Matchers +// ---------------------------------------------------------------------------- + +// matcher types try to match a request. +type matcher interface { + Match(*http.Request, *RouteMatch) bool +} + +// addMatcher adds a matcher to the route. +func (r *Route) addMatcher(m matcher) *Route { + if r.err == nil { + r.matchers = append(r.matchers, m) + } + return r +} + +// addRegexpMatcher adds a host or path matcher and builder to a route. +func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { + if r.err != nil { + return r.err + } + r.regexp = r.getRegexpGroup() + if !matchHost && !matchQuery { + if len(tpl) == 0 || tpl[0] != '/' { + return fmt.Errorf("mux: path must start with a slash, got %q", tpl) + } + if r.regexp.path != nil { + tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl + } + } + rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash) + if err != nil { + return err + } + for _, q := range r.regexp.queries { + if err = uniqueVars(rr.varsN, q.varsN); err != nil { + return err + } + } + if matchHost { + if r.regexp.path != nil { + if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { + return err + } + } + r.regexp.host = rr + } else { + if r.regexp.host != nil { + if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { + return err + } + } + if matchQuery { + r.regexp.queries = append(r.regexp.queries, rr) + } else { + r.regexp.path = rr + } + } + r.addMatcher(rr) + return nil +} + +// Headers -------------------------------------------------------------------- + +// headerMatcher matches the request against header values. +type headerMatcher map[string]string + +func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchMapWithString(m, r.Header, true) +} + +// Headers adds a matcher for request header values. +// It accepts a sequence of key/value pairs to be matched. For example: +// +// r := mux.NewRouter() +// r.Headers("Content-Type", "application/json", +// "X-Requested-With", "XMLHttpRequest") +// +// The above route will only match if both request header values match. +// If the value is an empty string, it will match any value if the key is set. +func (r *Route) Headers(pairs ...string) *Route { + if r.err == nil { + var headers map[string]string + headers, r.err = mapFromPairsToString(pairs...) + return r.addMatcher(headerMatcher(headers)) + } + return r +} + +// headerRegexMatcher matches the request against the route given a regex for the header +type headerRegexMatcher map[string]*regexp.Regexp + +func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchMapWithRegex(m, r.Header, true) +} + +// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex +// support. For example: +// +// r := mux.NewRouter() +// r.HeadersRegexp("Content-Type", "application/(text|json)", +// "X-Requested-With", "XMLHttpRequest") +// +// The above route will only match if both the request header matches both regular expressions. +// It the value is an empty string, it will match any value if the key is set. +func (r *Route) HeadersRegexp(pairs ...string) *Route { + if r.err == nil { + var headers map[string]*regexp.Regexp + headers, r.err = mapFromPairsToRegex(pairs...) + return r.addMatcher(headerRegexMatcher(headers)) + } + return r +} + +// Host ----------------------------------------------------------------------- + +// Host adds a matcher for the URL host. +// It accepts a template with zero or more URL variables enclosed by {}. +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next dot. +// +// - {name:pattern} matches the given regexp pattern. +// +// For example: +// +// r := mux.NewRouter() +// r.Host("www.example.com") +// r.Host("{subdomain}.domain.com") +// r.Host("{subdomain:[a-z]+}.domain.com") +// +// Variable names must be unique in a given route. They can be retrieved +// calling mux.Vars(request). +func (r *Route) Host(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, true, false, false) + return r +} + +// MatcherFunc ---------------------------------------------------------------- + +// MatcherFunc is the function signature used by custom matchers. +type MatcherFunc func(*http.Request, *RouteMatch) bool + +// Match returns the match for a given request. +func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { + return m(r, match) +} + +// MatcherFunc adds a custom function to be used as request matcher. +func (r *Route) MatcherFunc(f MatcherFunc) *Route { + return r.addMatcher(f) +} + +// Methods -------------------------------------------------------------------- + +// methodMatcher matches the request against HTTP methods. +type methodMatcher []string + +func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchInArray(m, r.Method) +} + +// Methods adds a matcher for HTTP methods. +// It accepts a sequence of one or more methods to be matched, e.g.: +// "GET", "POST", "PUT". +func (r *Route) Methods(methods ...string) *Route { + for k, v := range methods { + methods[k] = strings.ToUpper(v) + } + return r.addMatcher(methodMatcher(methods)) +} + +// Path ----------------------------------------------------------------------- + +// Path adds a matcher for the URL path. +// It accepts a template with zero or more URL variables enclosed by {}. The +// template must start with a "/". +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next slash. +// +// - {name:pattern} matches the given regexp pattern. +// +// For example: +// +// r := mux.NewRouter() +// r.Path("/products/").Handler(ProductsHandler) +// r.Path("/products/{key}").Handler(ProductsHandler) +// r.Path("/articles/{category}/{id:[0-9]+}"). +// Handler(ArticleHandler) +// +// Variable names must be unique in a given route. They can be retrieved +// calling mux.Vars(request). +func (r *Route) Path(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, false, false, false) + return r +} + +// PathPrefix ----------------------------------------------------------------- + +// PathPrefix adds a matcher for the URL path prefix. This matches if the given +// template is a prefix of the full URL path. See Route.Path() for details on +// the tpl argument. +// +// Note that it does not treat slashes specially ("/foobar/" will be matched by +// the prefix "/foo") so you may want to use a trailing slash here. +// +// Also note that the setting of Router.StrictSlash() has no effect on routes +// with a PathPrefix matcher. +func (r *Route) PathPrefix(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, false, true, false) + return r +} + +// Query ---------------------------------------------------------------------- + +// Queries adds a matcher for URL query values. +// It accepts a sequence of key/value pairs. Values may define variables. +// For example: +// +// r := mux.NewRouter() +// r.Queries("foo", "bar", "id", "{id:[0-9]+}") +// +// The above route will only match if the URL contains the defined queries +// values, e.g.: ?foo=bar&id=42. +// +// It the value is an empty string, it will match any value if the key is set. +// +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next slash. +// +// - {name:pattern} matches the given regexp pattern. +func (r *Route) Queries(pairs ...string) *Route { + length := len(pairs) + if length%2 != 0 { + r.err = fmt.Errorf( + "mux: number of parameters must be multiple of 2, got %v", pairs) + return nil + } + for i := 0; i < length; i += 2 { + if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { + return r + } + } + + return r +} + +// Schemes -------------------------------------------------------------------- + +// schemeMatcher matches the request against URL schemes. +type schemeMatcher []string + +func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchInArray(m, r.URL.Scheme) +} + +// Schemes adds a matcher for URL schemes. +// It accepts a sequence of schemes to be matched, e.g.: "http", "https". +func (r *Route) Schemes(schemes ...string) *Route { + for k, v := range schemes { + schemes[k] = strings.ToLower(v) + } + return r.addMatcher(schemeMatcher(schemes)) +} + +// BuildVarsFunc -------------------------------------------------------------- + +// BuildVarsFunc is the function signature used by custom build variable +// functions (which can modify route variables before a route's URL is built). +type BuildVarsFunc func(map[string]string) map[string]string + +// BuildVarsFunc adds a custom function to be used to modify build variables +// before a route's URL is built. +func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { + r.buildVarsFunc = f + return r +} + +// Subrouter ------------------------------------------------------------------ + +// Subrouter creates a subrouter for the route. +// +// It will test the inner routes only if the parent route matched. For example: +// +// r := mux.NewRouter() +// s := r.Host("www.example.com").Subrouter() +// s.HandleFunc("/products/", ProductsHandler) +// s.HandleFunc("/products/{key}", ProductHandler) +// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) +// +// Here, the routes registered in the subrouter won't be tested if the host +// doesn't match. +func (r *Route) Subrouter() *Router { + router := &Router{parent: r, strictSlash: r.strictSlash} + r.addMatcher(router) + return router +} + +// ---------------------------------------------------------------------------- +// URL building +// ---------------------------------------------------------------------------- + +// URL builds a URL for the route. +// +// It accepts a sequence of key/value pairs for the route variables. For +// example, given this route: +// +// r := mux.NewRouter() +// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). +// Name("article") +// +// ...a URL for it can be built using: +// +// url, err := r.Get("article").URL("category", "technology", "id", "42") +// +// ...which will return an url.URL with the following path: +// +// "/articles/technology/42" +// +// This also works for host variables: +// +// r := mux.NewRouter() +// r.Host("{subdomain}.domain.com"). +// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). +// Name("article") +// +// // url.String() will be "http://news.domain.com/articles/technology/42" +// url, err := r.Get("article").URL("subdomain", "news", +// "category", "technology", +// "id", "42") +// +// All variables defined in the route are required, and their values must +// conform to the corresponding patterns. +func (r *Route) URL(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp == nil { + return nil, errors.New("mux: route doesn't have a host or path") + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + var scheme, host, path string + if r.regexp.host != nil { + // Set a default scheme. + scheme = "http" + if host, err = r.regexp.host.url(values); err != nil { + return nil, err + } + } + if r.regexp.path != nil { + if path, err = r.regexp.path.url(values); err != nil { + return nil, err + } + } + return &url.URL{ + Scheme: scheme, + Host: host, + Path: path, + }, nil +} + +// URLHost builds the host part of the URL for a route. See Route.URL(). +// +// The route must have a host defined. +func (r *Route) URLHost(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp == nil || r.regexp.host == nil { + return nil, errors.New("mux: route doesn't have a host") + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + host, err := r.regexp.host.url(values) + if err != nil { + return nil, err + } + return &url.URL{ + Scheme: "http", + Host: host, + }, nil +} + +// URLPath builds the path part of the URL for a route. See Route.URL(). +// +// The route must have a path defined. +func (r *Route) URLPath(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp == nil || r.regexp.path == nil { + return nil, errors.New("mux: route doesn't have a path") + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + path, err := r.regexp.path.url(values) + if err != nil { + return nil, err + } + return &url.URL{ + Path: path, + }, nil +} + +// GetPathTemplate returns the template used to build the +// route match. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define a path. +func (r *Route) GetPathTemplate() (string, error) { + if r.err != nil { + return "", r.err + } + if r.regexp == nil || r.regexp.path == nil { + return "", errors.New("mux: route doesn't have a path") + } + return r.regexp.path.template, nil +} + +// GetHostTemplate returns the template used to build the +// route match. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define a host. +func (r *Route) GetHostTemplate() (string, error) { + if r.err != nil { + return "", r.err + } + if r.regexp == nil || r.regexp.host == nil { + return "", errors.New("mux: route doesn't have a host") + } + return r.regexp.host.template, nil +} + +// prepareVars converts the route variable pairs into a map. If the route has a +// BuildVarsFunc, it is invoked. +func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { + m, err := mapFromPairsToString(pairs...) + if err != nil { + return nil, err + } + return r.buildVars(m), nil +} + +func (r *Route) buildVars(m map[string]string) map[string]string { + if r.parent != nil { + m = r.parent.buildVars(m) + } + if r.buildVarsFunc != nil { + m = r.buildVarsFunc(m) + } + return m +} + +// ---------------------------------------------------------------------------- +// parentRoute +// ---------------------------------------------------------------------------- + +// parentRoute allows routes to know about parent host and path definitions. +type parentRoute interface { + getNamedRoutes() map[string]*Route + getRegexpGroup() *routeRegexpGroup + buildVars(map[string]string) map[string]string +} + +// getNamedRoutes returns the map where named routes are registered. +func (r *Route) getNamedRoutes() map[string]*Route { + if r.parent == nil { + // During tests router is not always set. + r.parent = NewRouter() + } + return r.parent.getNamedRoutes() +} + +// getRegexpGroup returns regexp definitions from this route. +func (r *Route) getRegexpGroup() *routeRegexpGroup { + if r.regexp == nil { + if r.parent == nil { + // During tests router is not always set. + r.parent = NewRouter() + } + regexp := r.parent.getRegexpGroup() + if regexp == nil { + r.regexp = new(routeRegexpGroup) + } else { + // Copy. + r.regexp = &routeRegexpGroup{ + host: regexp.host, + path: regexp.path, + queries: regexp.queries, + } + } + } + return r.regexp +} diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md index a9f7d88ef5..2cc5165042 100644 --- a/vendor/github.com/pkg/errors/README.md +++ b/vendor/github.com/pkg/errors/README.md @@ -3,7 +3,7 @@ Package errors implements functions for manipulating errors. The traditional error handling idiom in Go is roughly akin to -``` +```go if err != nil { return err } @@ -13,7 +13,7 @@ which applied recursively up the call stack results in error reports without con ## Adding context to an error The errors.Wrap function returns a new error that adds context to the original error. For example -``` +```go _, err := ioutil.ReadAll(r) if err != nil { return errors.Wrap(err, "read failed") @@ -24,13 +24,13 @@ In addition, `errors.Wrap` records the file and line where it was called, allowi ## Retrieving the cause of an error Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to recurse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -``` +```go type causer interface { Cause() error } ``` `errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -``` +```go switch err := errors.Cause(err).(type) { case *MyError: // handle specifically diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml index e11869ba32..2bbf623121 100644 --- a/vendor/github.com/spf13/cobra/.travis.yml +++ b/vendor/github.com/spf13/cobra/.travis.yml @@ -1,9 +1,14 @@ language: go go: - - 1.3.3 - - 1.4.2 - - 1.5.1 + - 1.4.3 + - 1.5.4 + - 1.6.2 - tip + +matrix: + allow_failures: + - go: tip + before_install: - mkdir -p bin - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go b/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go index 35192558f8..bc72bf6428 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go +++ b/vendor/golang.org/x/tools/go/gcimporter15/bexport_test.go @@ -11,10 +11,12 @@ import ( "go/ast" "go/build" "go/constant" + "go/parser" "go/token" "go/types" "reflect" "runtime" + "strings" "testing" "golang.org/x/tools/go/buildutil" @@ -66,7 +68,8 @@ type UnknownType undefined exportdata := gcimporter.BExportData(conf.Fset, pkg) imports := make(map[string]*types.Package) - n, pkg2, err := gcimporter.BImportData(imports, exportdata, pkg.Path()) + fset2 := token.NewFileSet() + n, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg.Path()) if err != nil { t.Errorf("BImportData(%s): %v", pkg.Path(), err) continue @@ -87,6 +90,14 @@ type UnknownType undefined t.Errorf("%s.%s not found, want %s", pkg.Path(), name, obj1) continue } + + fl1 := fileLine(conf.Fset, obj1) + fl2 := fileLine(fset2, obj2) + if fl1 != fl2 { + t.Errorf("%s.%s: got posn %s, want %s", + pkg.Path(), name, fl2, fl1) + } + if err := equalObj(obj1, obj2); err != nil { t.Errorf("%s.%s: %s\ngot: %s\nwant: %s", pkg.Path(), name, err, obj2, obj1) @@ -95,6 +106,11 @@ type UnknownType undefined } } +func fileLine(fset *token.FileSet, obj types.Object) string { + posn := fset.Position(obj.Pos()) + return fmt.Sprintf("%s:%d", posn.Filename, posn.Line) +} + // equalObj reports how x and y differ. They are assumed to belong to // different universes so cannot be compared directly. func equalObj(x, y types.Object) error { @@ -273,3 +289,40 @@ func equalType(x, y types.Type) error { } return nil } + +// TestVeryLongFile tests the position of an import object declared in +// a very long input file. Line numbers greater than maxlines are +// reported as line 1, not garbage or token.NoPos. +func TestVeryLongFile(t *testing.T) { + // parse and typecheck + longFile := "package foo" + strings.Repeat("\n", 123456) + "var X int" + fset1 := token.NewFileSet() + f, err := parser.ParseFile(fset1, "foo.go", longFile, 0) + if err != nil { + t.Fatal(err) + } + var conf types.Config + pkg, err := conf.Check("foo", fset1, []*ast.File{f}, nil) + if err != nil { + t.Fatal(err) + } + + // export + exportdata := gcimporter.BExportData(fset1, pkg) + + // import + imports := make(map[string]*types.Package) + fset2 := token.NewFileSet() + _, pkg2, err := gcimporter.BImportData(fset2, imports, exportdata, pkg.Path()) + if err != nil { + t.Fatalf("BImportData(%s): %v", pkg.Path(), err) + } + + // compare + posn1 := fset1.Position(pkg.Scope().Lookup("X").Pos()) + posn2 := fset2.Position(pkg2.Scope().Lookup("X").Pos()) + if want := "foo.go:1:1"; posn2.String() != want { + t.Errorf("X position = %s, want %s (orig was %s)", + posn2, want, posn1) + } +} diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bimport.go b/vendor/golang.org/x/tools/go/gcimporter15/bimport.go index a742dbfd28..e6b4863ea4 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/bimport.go +++ b/vendor/golang.org/x/tools/go/gcimporter15/bimport.go @@ -16,6 +16,7 @@ import ( "go/types" "sort" "strings" + "sync" "unicode" "unicode/utf8" ) @@ -35,6 +36,8 @@ type importer struct { posInfoFormat bool prevFile string prevLine int + fset *token.FileSet + files map[string]*token.File // debugging support debugFormat bool @@ -45,12 +48,14 @@ type importer struct { // and returns the number of bytes consumed and a reference to the package. // If data is obviously malformed, an error is returned but in // general it is not recommended to call BImportData on untrusted data. -func BImportData(imports map[string]*types.Package, data []byte, path string) (int, *types.Package, error) { +func BImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (int, *types.Package, error) { p := importer{ imports: imports, data: data, path: path, strList: []string{""}, // empty string is mapped to 0 + fset: fset, + files: make(map[string]*token.File), } // read low-level encoding format @@ -173,37 +178,37 @@ func (p *importer) declare(obj types.Object) { func (p *importer) obj(tag int) { switch tag { case constTag: - p.pos() + pos := p.pos() pkg, name := p.qualifiedName() typ := p.typ(nil) val := p.value() - p.declare(types.NewConst(token.NoPos, pkg, name, typ, val)) + p.declare(types.NewConst(pos, pkg, name, typ, val)) case typeTag: _ = p.typ(nil) case varTag: - p.pos() + pos := p.pos() pkg, name := p.qualifiedName() typ := p.typ(nil) - p.declare(types.NewVar(token.NoPos, pkg, name, typ)) + p.declare(types.NewVar(pos, pkg, name, typ)) case funcTag: - p.pos() + pos := p.pos() pkg, name := p.qualifiedName() params, isddd := p.paramList() result, _ := p.paramList() sig := types.NewSignature(nil, params, result, isddd) - p.declare(types.NewFunc(token.NoPos, pkg, name, sig)) + p.declare(types.NewFunc(pos, pkg, name, sig)) default: panic(fmt.Sprintf("unexpected object tag %d", tag)) } } -func (p *importer) pos() { +func (p *importer) pos() token.Pos { if !p.posInfoFormat { - return + return token.NoPos } file := p.prevFile @@ -219,9 +224,40 @@ func (p *importer) pos() { } p.prevLine = line - // TODO(gri) register new position + // Synthesize a token.Pos + + // Since we don't know the set of needed file positions, we + // reserve maxlines positions per file. + const maxlines = 64 * 1024 + f := p.files[file] + if f == nil { + f = p.fset.AddFile(file, -1, maxlines) + p.files[file] = f + // Allocate the fake linebreak indices on first use. + // TODO(adonovan): opt: save ~512KB using a more complex scheme? + fakeLinesOnce.Do(func() { + fakeLines = make([]int, maxlines) + for i := range fakeLines { + fakeLines[i] = i + } + }) + f.SetLines(fakeLines) + } + + if line > maxlines { + line = 1 + } + + // Treat the file as if it contained only newlines + // and column=1: use the line number as the offset. + return f.Pos(line - 1) } +var ( + fakeLines []int + fakeLinesOnce sync.Once +) + func (p *importer) qualifiedName() (pkg *types.Package, name string) { name = p.string() pkg = p.pkg() @@ -257,14 +293,14 @@ func (p *importer) typ(parent *types.Package) types.Type { switch i { case namedTag: // read type object - p.pos() + pos := p.pos() parent, name := p.qualifiedName() scope := parent.Scope() obj := scope.Lookup(name) // if the object doesn't exist yet, create and insert it if obj == nil { - obj = types.NewTypeName(token.NoPos, parent, name, nil) + obj = types.NewTypeName(pos, parent, name, nil) scope.Insert(obj) } @@ -290,7 +326,7 @@ func (p *importer) typ(parent *types.Package) types.Type { // read associated methods for i := p.int(); i > 0; i-- { // TODO(gri) replace this with something closer to fieldName - p.pos() + pos := p.pos() name := p.string() if !exported(name) { p.pkg() @@ -301,7 +337,7 @@ func (p *importer) typ(parent *types.Package) types.Type { result, _ := p.paramList() sig := types.NewSignature(recv.At(0), params, result, isddd) - t0.AddMethod(types.NewFunc(token.NoPos, parent, name, sig)) + t0.AddMethod(types.NewFunc(pos, parent, name, sig)) } return t @@ -415,7 +451,7 @@ func (p *importer) fieldList(parent *types.Package) (fields []*types.Var, tags [ } func (p *importer) field(parent *types.Package) *types.Var { - p.pos() + pos := p.pos() pkg, name := p.fieldName(parent) typ := p.typ(parent) @@ -434,7 +470,7 @@ func (p *importer) field(parent *types.Package) *types.Var { anonymous = true } - return types.NewField(token.NoPos, pkg, name, typ, anonymous) + return types.NewField(pos, pkg, name, typ, anonymous) } func (p *importer) methodList(parent *types.Package) (methods []*types.Func) { @@ -448,12 +484,12 @@ func (p *importer) methodList(parent *types.Package) (methods []*types.Func) { } func (p *importer) method(parent *types.Package) *types.Func { - p.pos() + pos := p.pos() pkg, name := p.fieldName(parent) params, isddd := p.paramList() result, _ := p.paramList() sig := types.NewSignature(nil, params, result, isddd) - return types.NewFunc(token.NoPos, pkg, name, sig) + return types.NewFunc(pos, pkg, name, sig) } func (p *importer) fieldName(parent *types.Package) (*types.Package, string) { diff --git a/vendor/golang.org/x/tools/go/gcimporter15/gcimporter.go b/vendor/golang.org/x/tools/go/gcimporter15/gcimporter.go index e1022103cd..4416739b12 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/gcimporter.go +++ b/vendor/golang.org/x/tools/go/gcimporter15/gcimporter.go @@ -174,7 +174,8 @@ func Import(packages map[string]*types.Package, path, srcDir string) (pkg *types var data []byte data, err = ioutil.ReadAll(buf) if err == nil { - _, pkg, err = BImportData(packages, data, path) + fset := token.NewFileSet() + _, pkg, err = BImportData(fset, packages, data, path) return } default: diff --git a/vendor/golang.org/x/tools/godoc/static/package.html b/vendor/golang.org/x/tools/godoc/static/package.html index 7f38c51a58..549825bb33 100644 --- a/vendor/golang.org/x/tools/godoc/static/package.html +++ b/vendor/golang.org/x/tools/godoc/static/package.html @@ -165,7 +165,9 @@

Variables

{{range .Funcs}} {{/* Name is a string - no need for FSet */}} {{$name_html := html .Name}} -

func {{$name_html}}

+

func {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{example_html $ .Name}} @@ -175,7 +177,9 @@

func {{$name_html}}type {{$tname_html}}

+

type {{$tname_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} @@ -195,7 +199,9 @@

type {{$tname_html}}< {{range .Funcs}} {{$name_html := html .Name}} -

func {{$name_html}}

+

func {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{example_html $ .Name}} @@ -204,7 +210,9 @@

func {{$name_html}}func ({{html .Recv}}) {{$name_html}}

+

func ({{html .Recv}}) {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{$name := printf "%s_%s" $tname .Name}} diff --git a/vendor/golang.org/x/tools/godoc/static/static.go b/vendor/golang.org/x/tools/godoc/static/static.go index 6aadc86a84..1bb0bb897d 100644 --- a/vendor/golang.org/x/tools/godoc/static/static.go +++ b/vendor/golang.org/x/tools/godoc/static/static.go @@ -1748,7 +1748,9 @@ function cgAddChild(tree, ul, cgn) { {{range .Funcs}} {{/* Name is a string - no need for FSet */}} {{$name_html := html .Name}} -

func {{$name_html}}

+

func {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{example_html $ .Name}} @@ -1758,7 +1760,9 @@ function cgAddChild(tree, ul, cgn) { {{range .Types}} {{$tname := .Name}} {{$tname_html := html .Name}} -

type {{$tname_html}}

+

type {{$tname_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} @@ -1778,7 +1782,9 @@ function cgAddChild(tree, ul, cgn) { {{range .Funcs}} {{$name_html := html .Name}} -

func {{$name_html}}

+

func {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{example_html $ .Name}} @@ -1787,7 +1793,9 @@ function cgAddChild(tree, ul, cgn) { {{range .Methods}} {{$name_html := html .Name}} -

func ({{html .Recv}}) {{$name_html}}

+

func ({{html .Recv}}) {{$name_html}} + +

{{node_html $ .Decl true}}
{{comment_html .Doc}} {{$name := printf "%s_%s" $tname .Name}} @@ -2826,6 +2834,14 @@ a:hover, .exampleHeading .text:hover { text-decoration: underline; } + +.permalink { + display: none; +} +h2:hover .permalink, h3:hover .permalink { + display: inline; +} + p, li { max-width: 800px; word-wrap: break-word; diff --git a/vendor/golang.org/x/tools/godoc/static/style.css b/vendor/golang.org/x/tools/godoc/static/style.css index 8ea08525f3..fd26bd85fc 100644 --- a/vendor/golang.org/x/tools/godoc/static/style.css +++ b/vendor/golang.org/x/tools/godoc/static/style.css @@ -42,6 +42,14 @@ a:hover, .exampleHeading .text:hover { text-decoration: underline; } + +.permalink { + display: none; +} +h2:hover .permalink, h3:hover .permalink { + display: inline; +} + p, li { max-width: 800px; word-wrap: break-word; From 1f25d9c1062b64b16884c00c4a9fbcaef1493f5c Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Wed, 11 May 2016 09:39:28 -0700 Subject: [PATCH 2/9] Refactor compiler interface slightly --- ast/compile.go | 4 ++-- ast/compile_test.go | 20 ++++++++++---------- eval/storage.go | 6 +++--- eval/topdown_test.go | 13 +++++++------ runtime/repl.go | 8 ++++---- 5 files changed, 26 insertions(+), 25 deletions(-) diff --git a/ast/compile.go b/ast/compile.go index 0ab90215b4..9ce0aed353 100644 --- a/ast/compile.go +++ b/ast/compile.go @@ -22,7 +22,7 @@ type Compiler struct { // Modules contains the compiled modules. The compiled modules are the // output of the compilation process. If the compilation process failed, // there is no guarantee about the state of the modules. - Modules []*Module + Modules map[string]*Module // Exports contains a mapping of package paths to variables. The variables // represent externally accessible symbols. For now the only type of @@ -71,7 +71,7 @@ func NewCompiler() *Compiler { // Compile runs the compilation process on the input modules. // The output of the compilation process can be obtained from // the Errors or Modules attributes of the Compiler. -func (c *Compiler) Compile(mods []*Module) { +func (c *Compiler) Compile(mods map[string]*Module) { // TODO(tsandall): should the modules be deep copied? c.Modules = mods diff --git a/ast/compile_test.go b/ast/compile_test.go index 3dcfab7716..811c0cae9e 100644 --- a/ast/compile_test.go +++ b/ast/compile_test.go @@ -22,7 +22,7 @@ func TestCompilerExample(t *testing.T) { if err != nil { panic(err) } - c.Compile([]*Module{m}) + c.Compile(map[string]*Module{"testMod": m}) assertNotFailed(t, c) } @@ -46,20 +46,20 @@ func TestCompilerSetGlobals(t *testing.T) { c.setGlobals() assertNotFailed(t, c) - assertGlobals(t, c, c.Modules[3], "{}") - assertGlobals(t, c, c.Modules[2], `{ + assertGlobals(t, c, c.Modules["mod4"], "{}") + assertGlobals(t, c, c.Modules["mod1"], `{ r: data.a.b.c.r, p: data.a.b.c.p, q: data.a.b.c.q, z: data.a.b.c.z, foo: data.x.y.z, k: data.g.h.k}`) - assertGlobals(t, c, c.Modules[1], `{ + assertGlobals(t, c, c.Modules["mod3"], `{ t: data.a.b.d.t, x: data.a.b.d.x, y: x, req: req}`) - assertGlobals(t, c, c.Modules[0], `{ + assertGlobals(t, c, c.Modules["mod2"], `{ r: data.a.b.c.r, p: data.x.y.p, q: data.a.b.c.q, @@ -77,7 +77,7 @@ func TestCompilerResolveAllRefs(t *testing.T) { assertNotFailed(t, c) - mod1 := c.Modules[2] + mod1 := c.Modules["mod1"] p := mod1.Rules[0] expr1 := p.Body[0] term := expr1.Terms.(*Term) @@ -93,7 +93,7 @@ func TestCompilerResolveAllRefs(t *testing.T) { t.Errorf("Wrong term (global in same package/diff module): expected %v but got: %v", e, term) } - mod2 := c.Modules[0] + mod2 := c.Modules["mod2"] r := mod2.Rules[0] expr3 := r.Body[1] term = expr3.Terms.([]*Term)[1] @@ -102,7 +102,7 @@ func TestCompilerResolveAllRefs(t *testing.T) { t.Errorf("Wrong term (var import): expected %v but got: %v", e, term) } - mod3 := c.Modules[1] + mod3 := c.Modules["mod3"] expr4 := mod3.Rules[0].Body[0] term = expr4.Terms.([]*Term)[2] e = MustParseTerm("{x.secret: [x.keyid]}") @@ -195,7 +195,7 @@ func assertNotFailed(t *testing.T, c *Compiler) { } } -func getCompilerTestModules() []*Module { +func getCompilerTestModules() map[string]*Module { mod1 := MustParseModule(` package a.b.c @@ -227,5 +227,5 @@ func getCompilerTestModules() []*Module { package a.b.empty `) - return []*Module{mod2, mod3, mod1, mod4} + return map[string]*Module{"mod2": mod2, "mod3": mod3, "mod1": mod1, "mod4": mod4} } diff --git a/eval/storage.go b/eval/storage.go index 946d4c9d26..9ab7809f40 100644 --- a/eval/storage.go +++ b/eval/storage.go @@ -84,7 +84,7 @@ func NewEmptyStorage() *Storage { // NewStorage is a helper for creating a new Storage containing // the given base documents and rules. -func NewStorage(docs []map[string]interface{}, mods []*ast.Module) (*Storage, error) { +func NewStorage(docs []map[string]interface{}, mods map[string]*ast.Module) (*Storage, error) { store := NewEmptyStorage() @@ -147,13 +147,13 @@ func NewStorage(docs []map[string]interface{}, mods []*ast.Module) (*Storage, er // documents stored in files and/or policy modules. func NewStorageFromFiles(files []string) (*Storage, error) { - modules := []*ast.Module{} + modules := map[string]*ast.Module{} docs := []map[string]interface{}{} for _, file := range files { m, astErr := ast.ParseModuleFile(file) if astErr == nil { - modules = append(modules, m) + modules[file] = m continue } d, jsonErr := parseJSONObjectFile(file) diff --git a/eval/topdown_test.go b/eval/topdown_test.go index f1c0d64d1e..7de14e4e5c 100644 --- a/eval/topdown_test.go +++ b/eval/topdown_test.go @@ -602,12 +602,13 @@ func TestExample(t *testing.T) { `) } -func compileModules(input []string) []*ast.Module { +func compileModules(input []string) map[string]*ast.Module { - mods := []*ast.Module{} + mods := map[string]*ast.Module{} - for _, i := range input { - mods = append(mods, ast.MustParseModule(i)) + for idx, i := range input { + id := fmt.Sprintf("testMod%d", idx) + mods[id] = ast.MustParseModule(i) } c := ast.NewCompiler() @@ -618,7 +619,7 @@ func compileModules(input []string) []*ast.Module { return c.Modules } -func compileRules(imports []string, input []string) []*ast.Module { +func compileRules(imports []string, input []string) map[string]*ast.Module { rules := []*ast.Rule{} for _, i := range input { @@ -642,7 +643,7 @@ func compileRules(imports []string, input []string) []*ast.Module { } c := ast.NewCompiler() - if c.Compile([]*ast.Module{m}); c.Failed() { + if c.Compile(map[string]*ast.Module{"testMod": m}); c.Failed() { panic(c.FlattenErrors()) } diff --git a/runtime/repl.go b/runtime/repl.go index a1dcd7973b..5b9dac0764 100644 --- a/runtime/repl.go +++ b/runtime/repl.go @@ -170,11 +170,11 @@ func (r *Repl) compileBody(body ast.Body) (ast.Body, error) { Rules: []*ast.Rule{rule}, } c := ast.NewCompiler() - c.Compile([]*ast.Module{m}) + c.Compile(map[string]*ast.Module{"tmp": m}) if len(c.Errors) > 0 { return nil, fmt.Errorf(c.FlattenErrors()) } - return c.Modules[0].Rules[0].Body, nil + return c.Modules["tmp"].Rules[0].Body, nil } func (r *Repl) compileRule(rule *ast.Rule) (*ast.Rule, error) { @@ -188,11 +188,11 @@ func (r *Repl) compileRule(rule *ast.Rule) (*ast.Rule, error) { Rules: []*ast.Rule{rule}, } c := ast.NewCompiler() - c.Compile([]*ast.Module{m}) + c.Compile(map[string]*ast.Module{"tmp": m}) if len(c.Errors) > 0 { return nil, fmt.Errorf(c.FlattenErrors()) } - return c.Modules[0].Rules[0], nil + return c.Modules["tmp"].Rules[0], nil } func (r *Repl) evalBufferOne() bool { From 12dad370d5b42e1e7d783d3b3382180841090eca Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Wed, 11 May 2016 09:08:56 -0700 Subject: [PATCH 3/9] Add basic REST API support to server mode - REST APIs * CRUDL on policy modules * Ad-hoc queries * Query and patch base documents * Query virtual documents - Add PolicyStore to manage policy definition/module CRUDL operations. * Supports persistence of policy definitons. * Serve REST API CRUDL operations. * Manage install/uninstall of rules into data store. * Manage persistence of policy definitions. - Misc. refactoring * Move storage creation into runtime Init. * Make AST types JSON serializable. Tweaked ast.Import to use Term instead of Value for the path. --- .gitignore | 8 +- Makefile | 7 +- ast/compile.go | 4 +- ast/parser_test.go | 8 +- ast/policy.go | 70 ++++- ast/policy_test.go | 95 ++++++- ast/rego.peg | 4 +- ast/term.go | 161 +++++++++++- ast/term_test.go | 41 ++- cmd/run.go | 36 ++- cmd/version.go | 9 +- eval/index.go | 14 +- eval/policystore.go | 321 +++++++++++++++++++++++ eval/policystore_test.go | 305 ++++++++++++++++++++++ eval/storage.go | 131 ++-------- eval/storage_test.go | 58 ----- eval/topdown.go | 21 +- eval/topdown_test.go | 40 ++- eval/tracer_test.go | 13 +- runtime/repl.go | 21 +- runtime/runtime.go | 199 +++++++++++++-- runtime/runtime_test.go | 125 +++++++++ runtime/server.go | 538 +++++++++++++++++++++++++++++++++++++++ runtime/server_test.go | 360 ++++++++++++++++++++++++++ 24 files changed, 2305 insertions(+), 284 deletions(-) create mode 100644 eval/policystore.go create mode 100644 eval/policystore_test.go create mode 100644 runtime/runtime_test.go create mode 100644 runtime/server.go create mode 100644 runtime/server_test.go diff --git a/.gitignore b/.gitignore index cd33ccefa2..9e3f5b8090 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,11 @@ +# development environment .DS_Store .vscode + +# build artifacts +coverage opa ast/parser.go -coverage + +# runtime artifacts +policies diff --git a/Makefile b/Makefile index ad6f9ed650..06ca9d5d9d 100644 --- a/Makefile +++ b/Makefile @@ -37,14 +37,17 @@ generate: build: generate $(GO) build -o opa $(LDFLAGS) +install: generate + $(GO) install $(LDFLAGS) + test: generate $(GO) test -v $(PACKAGES) COVER_PACKAGES=$(PACKAGES) $(COVER_PACKAGES): @mkdir -p coverage/$(shell dirname $@) - go test -covermode=count -coverprofile=coverage/$(shell dirname $@)/coverage.out $@ - go tool cover -html=coverage/$(shell dirname $@)/coverage.out || true + $(GO) test -covermode=count -coverprofile=coverage/$(shell dirname $@)/coverage.out $@ + $(GO) tool cover -html=coverage/$(shell dirname $@)/coverage.out || true cover: $(COVER_PACKAGES) diff --git a/ast/compile.go b/ast/compile.go index 9ce0aed353..fcc6803fbe 100644 --- a/ast/compile.go +++ b/ast/compile.go @@ -196,7 +196,7 @@ func (c *Compiler) setGlobals() { // Populate globals with imports within this module. for _, i := range m.Imports { if len(i.Alias) > 0 { - switch p := i.Path.(type) { + switch p := i.Path.Value.(type) { case Ref: globals[i.Alias] = p case Var: @@ -205,7 +205,7 @@ func (c *Compiler) setGlobals() { c.err("unexpected %T: %v", p, i) } } else { - switch p := i.Path.(type) { + switch p := i.Path.Value.(type) { case Ref: switch v := p[len(p)-1].Value.(type) { case String: diff --git a/ast/parser_test.go b/ast/parser_test.go index 6dfe37e250..cbb24a844e 100644 --- a/ast/parser_test.go +++ b/ast/parser_test.go @@ -200,12 +200,12 @@ func TestPackage(t *testing.T) { } func TestImport(t *testing.T) { - assertParseImport(t, "single", "import foo", &Import{Path: VarTerm("foo").Value}) - ref := RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value + assertParseImport(t, "single", "import foo", &Import{Path: VarTerm("foo")}) + ref := RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")) assertParseImport(t, "multiple", "import foo.bar.baz", &Import{Path: ref}) - assertParseImport(t, "single alias", "import foo as bar", &Import{Path: VarTerm("foo").Value, Alias: Var("bar")}) + assertParseImport(t, "single alias", "import foo as bar", &Import{Path: VarTerm("foo"), Alias: Var("bar")}) assertParseImport(t, "multiple alias", "import foo.bar.baz as qux", &Import{Path: ref, Alias: Var("qux")}) - ref2 := RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("white space")).Value + ref2 := RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("white space")) assertParseImport(t, "white space", "import foo.bar[\"white space\"]", &Import{Path: ref2}) assertParseError(t, "non-ground ref", "import foo[x]") } diff --git a/ast/policy.go b/ast/policy.go index 4c58fac2e1..84b939e7db 100644 --- a/ast/policy.go +++ b/ast/policy.go @@ -4,8 +4,11 @@ package ast -import "fmt" -import "strings" +import ( + "encoding/json" + "fmt" + "strings" +) // DefaultRootDocument is the default root document. // All package directives inside source files are implicitly @@ -31,25 +34,25 @@ type ( // Package represents the namespace of the documents produced // by rules inside the module. Package struct { - Location *Location + Location *Location `json:"-"` Path Ref } // Import represents a dependency on a document outside of the policy // namespace. Imports are optional. Import struct { - Location *Location - Path Value - Alias Var + Location *Location `json:"-"` + Path *Term + Alias Var `json:",omitempty"` } // Rule represents a rule as defined in the language. Rules define the // content of documents that represent policy decisions. Rule struct { - Location *Location + Location *Location `json:"-"` Name Var - Key *Term - Value *Term + Key *Term `json:",omitempty"` + Value *Term `json:",omitempty"` Body Body } @@ -58,8 +61,8 @@ type ( // Expr represents a single expression contained inside the body of a rule. Expr struct { - Location *Location - Negated bool + Location *Location `json:"-"` + Negated bool `json:",omitempty"` Terms interface{} } ) @@ -264,6 +267,51 @@ func (expr *Expr) String() string { return strings.Join(buf, " ") } +// UnmarshalJSON parses the byte array and stores the result in expr. +func (expr *Expr) UnmarshalJSON(bs []byte) error { + v := map[string]interface{}{} + if err := json.Unmarshal(bs, &v); err != nil { + return err + } + + n, ok := v["Negated"] + if !ok { + expr.Negated = false + } else { + b, ok := n.(bool) + if !ok { + return unmarshalError(n, "bool") + } + expr.Negated = b + } + + switch ts := v["Terms"].(type) { + case map[string]interface{}: + v, err := unmarshalValue(ts) + if err != nil { + return err + } + expr.Terms = &Term{Value: v} + case []interface{}: + buf := []*Term{} + for _, v := range ts { + e, ok := v.(map[string]interface{}) + if !ok { + return unmarshalError(v, "map[string]interface{}") + } + v, err := unmarshalValue(e) + if err != nil { + return err + } + buf = append(buf, &Term{Value: v}) + } + expr.Terms = buf + default: + return unmarshalError(v["Terms"], "Term or []Term") + } + return nil +} + // NewBuiltinExpr creates a new Expr object with the supplied terms. // The builtin operator must be the first term. func NewBuiltinExpr(terms ...*Term) *Expr { diff --git a/ast/policy_test.go b/ast/policy_test.go index 3879a6c0f3..d936f23040 100644 --- a/ast/policy_test.go +++ b/ast/policy_test.go @@ -4,7 +4,38 @@ package ast -import "testing" +import ( + "encoding/json" + "reflect" + "testing" +) + +func TestModuleJSONRoundTrip(t *testing.T) { + mod := MustParseModule(` + package a.b.c + import data.x.y as z + import data.u.i + p = [1,2,{"foo":3}] :- r[x] = 1, not q[x] + r[y] = v :- i[1] = y, v = i[2] + q[x] :- a=[true,false,null,{"x":[1,2,3]}], a[i] = x + `) + + bs, err := json.Marshal(mod) + if err != nil { + panic(err) + } + + roundtrip := &Module{} + + err = json.Unmarshal(bs, roundtrip) + if err != nil { + panic(err) + } + + if !roundtrip.Equal(mod) { + t.Errorf("Expected roundtripped module to be equal to original:\nExpected:\n\n%v\n\nGot:\n\n%v\n", mod, roundtrip) + } +} func TestPackageEquals(t *testing.T) { pkg1 := &Package{Path: RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value.(Ref)} @@ -26,12 +57,12 @@ func TestPackageString(t *testing.T) { } func TestImportEquals(t *testing.T) { - imp1 := &Import{Path: Var("foo"), Alias: Var("bar")} - imp11 := &Import{Path: Var("foo"), Alias: Var("bar")} - imp2 := &Import{Path: Var("foo")} - imp3 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux")).Value, Alias: Var("corge")} - imp33 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux")).Value, Alias: Var("corge")} - imp4 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux")).Value} + imp1 := &Import{Path: VarTerm("foo"), Alias: Var("bar")} + imp11 := &Import{Path: VarTerm("foo"), Alias: Var("bar")} + imp2 := &Import{Path: VarTerm("foo")} + imp3 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux")), Alias: Var("corge")} + imp33 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux")), Alias: Var("corge")} + imp4 := &Import{Path: RefTerm(VarTerm("bar"), VarTerm("baz"), VarTerm("qux"))} assertImportsEqual(t, imp1, imp1) assertImportsEqual(t, imp1, imp11) assertImportsEqual(t, imp3, imp3) @@ -47,10 +78,10 @@ func TestImportEquals(t *testing.T) { } func TestImportString(t *testing.T) { - imp1 := &Import{Path: Var("foo"), Alias: Var("bar")} - imp2 := &Import{Path: Var("foo")} - imp3 := &Import{Path: RefTerm(VarTerm("bar"), StringTerm("baz"), StringTerm("qux")).Value, Alias: Var("corge")} - imp4 := &Import{Path: RefTerm(VarTerm("bar"), StringTerm("baz"), StringTerm("qux")).Value} + imp1 := &Import{Path: VarTerm("foo"), Alias: Var("bar")} + imp2 := &Import{Path: VarTerm("foo")} + imp3 := &Import{Path: RefTerm(VarTerm("bar"), StringTerm("baz"), StringTerm("qux")), Alias: Var("corge")} + imp4 := &Import{Path: RefTerm(VarTerm("bar"), StringTerm("baz"), StringTerm("qux"))} assertImportToString(t, imp1, "import foo as bar") assertImportToString(t, imp2, "import foo") assertImportToString(t, imp3, "import bar.baz.qux as corge") @@ -126,6 +157,48 @@ func TextExprString(t *testing.T) { assertExprString(t, expr4, "ne({foo: [1, a.b]}, false)") } +func TestExprBadJSON(t *testing.T) { + + assert := func(js string, exp error) { + expr := Expr{} + err := json.Unmarshal([]byte(js), &expr) + if !reflect.DeepEqual(exp, err) { + t.Errorf("Expected %v but got: %v", exp, err) + } + } + + js := ` + { + "Negated": 100, + "Terms": { + "Value": "foo", + "Type": "string" + } + } + ` + + exp := unmarshalError(100.0, "bool") + assert(js, exp) + + js = ` + { + "Terms": [ + "foo" + ] + } + ` + exp = unmarshalError("foo", "map[string]interface{}") + assert(js, exp) + + js = ` + { + "Terms": "bad value" + } + ` + exp = unmarshalError("bad value", "Term or []Term") + assert(js, exp) +} + func TestRuleHeadEquals(t *testing.T) { assertRulesEqual(t, &Rule{}, &Rule{}) diff --git a/ast/rego.peg b/ast/rego.peg index 8b432307de..8bba07917b 100644 --- a/ast/rego.peg +++ b/ast/rego.peg @@ -74,8 +74,8 @@ Package <- "package" ws val:(Ref / Var) { Import <- "import" ws path:(Ref / Var) alias:(ws "as" ws Var)? { imp := &Import{} imp.Location = currentLocation(c) - imp.Path = path.(*Term).Value - switch p := imp.Path.(type) { + imp.Path = path.(*Term) + switch p := imp.Path.Value.(type) { case Ref: if !p.IsGround() { return nil, fmt.Errorf("import cannot contain variables in tail: %v", p) diff --git a/ast/term.go b/ast/term.go index e7c719e3a6..6fb07406f9 100644 --- a/ast/term.go +++ b/ast/term.go @@ -4,10 +4,14 @@ package ast -import "fmt" -import "regexp" -import "strconv" -import "strings" +import ( + "encoding/json" + "fmt" + "regexp" + "strconv" + "strings" +) + import "hash/fnv" // Location records a position in source code @@ -48,7 +52,7 @@ type Value interface { // Term is an argument to a function. type Term struct { Value Value // the value of the Term as represented in Go - Location *Location // the location of the Term in the source + Location *Location `json:"-"` // the location of the Term in the source } // Equal returns true if this term equals the other term. Equality is @@ -71,10 +75,55 @@ func (term *Term) IsGround() bool { return term.Value.IsGround() } +// MarshalJSON returns the JSON encoding of the term. +// Specialized marshalling logic is required to include a type hint +// for Value. +func (term *Term) MarshalJSON() ([]byte, error) { + var typ string + switch term.Value.(type) { + case Null: + typ = "null" + case Boolean: + typ = "boolean" + case Number: + typ = "number" + case String: + typ = "string" + case Ref: + typ = "ref" + case Var: + typ = "var" + case Array: + typ = "array" + case Object: + typ = "object" + } + d := map[string]interface{}{ + "Type": typ, + "Value": term.Value, + } + return json.Marshal(d) +} + func (term *Term) String() string { return term.Value.String() } +// UnmarshalJSON parses the byte array and stores the result in term. +// Specialized unmarshalling is required to handle Value. +func (term *Term) UnmarshalJSON(bs []byte) error { + v := map[string]interface{}{} + if err := json.Unmarshal(bs, &v); err != nil { + return err + } + val, err := unmarshalValue(v) + if err != nil { + return err + } + term.Value = val + return nil +} + // Null represents the null value defined by JSON. type Null struct{} @@ -590,3 +639,105 @@ func termSliceIsGround(a []*Term) bool { } return true } + +func unmarshalError(v interface{}, e string) error { + return fmt.Errorf("ast: cannot unmarshal %T into Go value of type %v", v, e) +} + +func unmarshalTermSlice(d map[string]interface{}) ([]*Term, error) { + s, ok := d["Value"].([]interface{}) + if !ok { + return nil, unmarshalError(d["Value"], "[]interface{}") + } + buf := []*Term{} + for _, i := range s { + m, ok := i.(map[string]interface{}) + if !ok { + return nil, unmarshalError(i, "map[string]interface{}") + } + v, err := unmarshalValue(m) + if err != nil { + return nil, err + } + buf = append(buf, &Term{Value: v}) + } + return buf, nil +} + +func unmarshalValue(d map[string]interface{}) (Value, error) { + switch d["Type"] { + case "null": + return Null{}, nil + case "boolean": + b, ok := d["Value"].(bool) + if !ok { + return nil, unmarshalError(d["Value"], "bool") + } + return Boolean(b), nil + case "number": + f, ok := d["Value"].(float64) + if !ok { + return nil, unmarshalError(d["Value"], "float64") + } + return Number(f), nil + case "string": + s, ok := d["Value"].(string) + if !ok { + return nil, unmarshalError(d["Value"], "string") + } + return String(s), nil + case "ref": + s, err := unmarshalTermSlice(d) + if err != nil { + return nil, err + } + return Ref(s), nil + case "var": + s, ok := d["Value"].(string) + if !ok { + return nil, unmarshalError(d["Value"], "ast.Var") + } + return Var(s), nil + case "array": + s, err := unmarshalTermSlice(d) + if err != nil { + return nil, err + } + return Array(s), nil + case "object": + buf := Object{} + s, ok := d["Value"].([]interface{}) + if !ok { + return nil, unmarshalError(d["Value"], "[]interface{}") + } + for _, i := range s { + p, ok := i.([]interface{}) + if !ok { + return nil, unmarshalError(i, "[]interface{}") + } + if len(p) != 2 { + return nil, unmarshalError(p, "[2]interface{}") + } + km, ok := p[0].(map[string]interface{}) + if !ok { + return nil, unmarshalError(p[0], "map[string]interface{}") + } + k, err := unmarshalValue(km) + if err != nil { + return nil, err + } + vm, ok := p[1].(map[string]interface{}) + if !ok { + return nil, unmarshalError(p[1], "map[string]interface{}") + } + v, err := unmarshalValue(vm) + if err != nil { + return nil, err + } + buf = append(buf, [2]*Term{&Term{Value: k}, &Term{Value: v}}) + } + return buf, nil + default: + return nil, fmt.Errorf("ast: cannot unmarshal Term with Type %v", d["Type"]) + } +} diff --git a/ast/term_test.go b/ast/term_test.go index e6b6a4641d..a6a697d51f 100644 --- a/ast/term_test.go +++ b/ast/term_test.go @@ -5,6 +5,7 @@ package ast import ( + "encoding/json" "fmt" "reflect" "sort" @@ -106,7 +107,43 @@ func TestQuery(t *testing.T) { } } -func TestEqualTerms(t *testing.T) { +func TestTermBadJSON(t *testing.T) { + + assert := func(js string, exp error) { + term := Term{} + err := json.Unmarshal([]byte(js), &term) + if !reflect.DeepEqual(exp, err) { + t.Errorf("Expected %v but got: %v", exp, err) + } + } + + castTests := []struct { + input string + val interface{} + expected string + }{ + {`{"Value": null, "Type": "boolean"}`, nil, "bool"}, + {`{"Value": false, "Type": "number"}`, false, "float64"}, + {`{"Value": 100, "Type": "string"}`, 100.0, "string"}, + {`{"Value": "hello", "Type": "number"}`, "hello", "float64"}, + {`{"Value": 100, "Type": "var"}`, 100.0, "ast.Var"}, + {`{"Value": "abc", "Type": "ref"}`, "abc", "[]interface{}"}, + {`{"Value": ["abc"], "Type": "ref"}`, "abc", "map[string]interface{}"}, + {`{"Value": "abc", "Type": "array"}`, "abc", "[]interface{}"}, + {`{"Value": ["abc"], "Type": "array"}`, "abc", "map[string]interface{}"}, + {`{"Value": "abc", "Type": "object"}`, "abc", "[]interface{}"}, + {`{"Value": ["abc"], "Type": "object"}`, "abc", "[]interface{}"}, + {`{"Value": [["abc"]], "Type": "object"}`, []interface{}{}, "[2]interface{}"}, + {`{"Value": [["abc", "abc"]], "Type": "object"}`, "abc", "map[string]interface{}"}, + {`{"Value": [[{"Value": "abc", "Type": "string"}, "abc"]], "Type": "object"}`, "abc", "map[string]interface{}"}, + } + + for _, tc := range castTests { + assert(tc.input, unmarshalError(tc.val, tc.expected)) + } +} + +func TestTermEqual(t *testing.T) { assertTermEqual(t, NullTerm(), NullTerm()) assertTermEqual(t, BooleanTerm(true), BooleanTerm(true)) assertTermEqual(t, NumberTerm(5), NumberTerm(5)) @@ -155,7 +192,7 @@ func TestHash(t *testing.T) { } } -func TestTermsToString(t *testing.T) { +func TestTermString(t *testing.T) { assertToString(t, Null{}, "null") assertToString(t, Boolean(true), "true") assertToString(t, Boolean(false), "false") diff --git a/cmd/run.go b/cmd/run.go index bc13bca4fb..00fd52addd 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -7,6 +7,7 @@ package cmd import ( "os" "path" + "path/filepath" "github.com/open-policy-agent/opa/runtime" "github.com/spf13/cobra" @@ -15,6 +16,12 @@ import ( // default filename for the interactive shell's history var defaultHistoryFile = ".opa_history" +// default policy definition storage directory +var defaultPolicyDir = "policies" + +// default listening address for the server +var defaultAddr = ":8181" + func init() { params := &runtime.Params{} @@ -24,6 +31,18 @@ func init() { Short: "Start OPA in interative or server mode", Long: `Start an instance of the Open Policy Agent (OPA). +To run the interactive shell: + + $ opa run + +To run the server without saving policies: + + $ opa run -s + +To run the server and persist policies to a local directory: + + $ opa run -s -p ./policies/ + The 'run' command starts an instance of the OPA runtime. The OPA runtime can be started as an interactive shell or a server. @@ -33,6 +52,11 @@ a server, users can access OPA's APIs via HTTP. The runtime can be initialized with one or more files that represent base documents (e.g., example.json) or policies (e.g., example.rego). + +If the --policy-dir option is specified any files inside the directory +will be considered policy definitions and will be loaded on startup. API +calls to create new policies save the definition file to this direcory. +In addition, API calls to delete policies will remove the definition file. `, Run: func(cmd *cobra.Command, args []string) { params.Paths = args @@ -43,10 +67,12 @@ base documents (e.g., example.json) or policies (e.g., example.rego). runCommand.Flags().BoolVarP(¶ms.Server, "server", "s", false, "start the runtime in server mode") runCommand.Flags().StringVarP(¶ms.HistoryPath, "history", "H", historyPath(), "set path of history file") + runCommand.Flags().StringVarP(¶ms.PolicyDir, "policy-dir", "p", "", "set directory to store policy definitions") + runCommand.Flags().StringVarP(¶ms.Addr, "addr", "a", defaultAddr, "set listening address of the server") usageTemplate := `Usage: {{.UseLine}} [flags] [files] - + Flags: {{.LocalFlags.FlagUsages | trimRightSpace}} ` @@ -63,3 +89,11 @@ func historyPath() string { } return path.Join(home, defaultHistoryFile) } + +func policyDir() string { + cwd, err := os.Getwd() + if err != nil { + return defaultPolicyDir + } + return filepath.Join(cwd, defaultPolicyDir) +} diff --git a/cmd/version.go b/cmd/version.go index 956157d7d9..ce1eb00191 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -4,9 +4,12 @@ package cmd -import "fmt" -import "github.com/spf13/cobra" -import "github.com/open-policy-agent/opa/version" +import ( + "fmt" + + "github.com/open-policy-agent/opa/version" + "github.com/spf13/cobra" +) var versionCommand = &cobra.Command{ Use: "version", diff --git a/eval/index.go b/eval/index.go index 5cd92410bd..4160105bd0 100644 --- a/eval/index.go +++ b/eval/index.go @@ -293,11 +293,8 @@ func iterStorage(store *Storage, ref ast.Ref, path ast.Ref, bindings *Bindings, if len(ref) == 0 { node, err := lookup(store, path) if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - return nil - } + if IsStorageNotFound(err) { + return nil } return err } @@ -318,11 +315,8 @@ func iterStorage(store *Storage, ref ast.Ref, path ast.Ref, bindings *Bindings, node, err := lookup(store, path) if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - return nil - } + if IsStorageNotFound(err) { + return nil } return err } diff --git a/eval/policystore.go b/eval/policystore.go new file mode 100644 index 0000000000..bebcfd8a16 --- /dev/null +++ b/eval/policystore.go @@ -0,0 +1,321 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package eval + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "strings" + + "github.com/open-policy-agent/opa/ast" + "github.com/pkg/errors" +) + +// PolicyStore provides a storage abstraction for policy definitions and modules. +// +type PolicyStore struct { + dataStore *Storage + policyDir string + raw map[string][]byte + modules map[string]*ast.Module +} + +// LoadPolicies is the default callback function that will be used when +// opening the policy store. +func LoadPolicies(bufs map[string][]byte) (map[string]*ast.Module, error) { + + parsed := map[string]*ast.Module{} + + for id, bs := range bufs { + mod, err := ast.ParseModule(string(bs)) + if err != nil { + return nil, err + } + parsed[id] = mod + } + + c := ast.NewCompiler() + if c.Compile(parsed); c.Failed() { + return nil, c.Errors[0] + } + + return c.Modules, nil +} + +// NewPolicyStore returns an empty PolicyStore. +func NewPolicyStore(store *Storage, policyDir string) *PolicyStore { + return &PolicyStore{ + dataStore: store, + policyDir: policyDir, + raw: map[string][]byte{}, + modules: map[string]*ast.Module{}, + } +} + +// List returns all of the modules. +func (p *PolicyStore) List() map[string]*ast.Module { + cpy := map[string]*ast.Module{} + for k, v := range p.modules { + cpy[k] = v + } + return cpy +} + +// Open initializes the policy store. +// +// This should be called on startup to load policies from persistent storage. +// The callback function "f" will be invoked with the buffers representing the +// persisted policies. The callback should return the compiled version of the +// policies so that they can be installed into the data store. +// +func (p *PolicyStore) Open(f func(map[string][]byte) (map[string]*ast.Module, error)) error { + + if len(p.policyDir) == 0 { + return nil + } + + info, err := ioutil.ReadDir(p.policyDir) + if err != nil { + return err + } + + raw := map[string][]byte{} + + for _, i := range info { + + f := i.Name() + bs, err := ioutil.ReadFile(filepath.Join(p.policyDir, f)) + + if err != nil { + return err + } + + id := p.getID(f) + raw[id] = bs + } + + mods, err := f(raw) + if err != nil { + return err + } + + for id, mod := range mods { + if err := p.Add(id, mod, raw[id], false); err != nil { + return err + } + } + + return nil +} + +// Add inserts the policy module into the store. If an existing policy module exists with the same ID, +// it is overwritten. If persist is false, then the policy will not be persisted. +func (p *PolicyStore) Add(id string, mod *ast.Module, raw []byte, persist bool) error { + + if persist && len(p.policyDir) == 0 { + return fmt.Errorf("cannot persist without --policy-dir set") + } + + old := p.modules[id] + + if old != nil { + if err := p.uninstallModule(old); err != nil { + return errors.Wrapf(err, "failed to uninstall old version of module: %v", id) + } + } + + if err := p.installModule(mod); err != nil { + return errors.Wrapf(err, "failed to install module but old version of module was uninstalled: %v", id) + } + + p.raw[id] = raw + p.modules[id] = mod + + if persist { + filename := p.getFilename(id) + if err := ioutil.WriteFile(filename, raw, 0644); err != nil { + return errors.Wrapf(err, "failed to persist definition but new version was installed: %v", id) + } + } + + return nil +} + +// Remove removes the policy module for id. +func (p *PolicyStore) Remove(id string) error { + + mod, err := p.Get(id) + if err != nil { + return err + } + + if err := p.uninstallModule(mod); err != nil { + return errors.Wrapf(err, "failed to uninstall module: %v", id) + } + + filename := p.getFilename(id) + + if strings.HasPrefix(filename, p.policyDir) { + if err := os.Remove(filename); err != nil { + if !os.IsNotExist(err) { + return errors.Wrapf(err, "failed to delete persisted definition but module was uninstalled: %v", id) + } + } + } + + delete(p.raw, id) + delete(p.modules, id) + + return nil +} + +// Get returns the policy module for id. +func (p *PolicyStore) Get(id string) (*ast.Module, error) { + mod, ok := p.modules[id] + if !ok { + return nil, notFoundErrorf("module not found: %v", id) + } + return mod, nil +} + +// GetRaw returns the raw content of the module for id. +func (p *PolicyStore) GetRaw(id string) ([]byte, error) { + bs, ok := p.raw[id] + if !ok { + return nil, notFoundErrorf("definition not found: %v", id) + } + return bs, nil +} + +func (p *PolicyStore) getFilename(id string) string { + return filepath.Join(p.policyDir, id) +} + +func (p *PolicyStore) getID(f string) string { + return filepath.Base(f) +} + +func (p *PolicyStore) installModule(mod *ast.Module) error { + + installed := map[*ast.Rule][]interface{}{} + + for _, r := range mod.Rules { + fqn := append(ast.Ref{}, mod.Package.Path...) + fqn = append(fqn, &ast.Term{Value: ast.String(r.Name)}) + path, _ := fqn.Underlying() + path = path[1:] + if err := p.installRule(path, r); err != nil { + for r, path := range installed { + if err := p.uninstallRule(path, r); err != nil { + return err + } + } + return err + } + installed[r] = path + } + + return nil +} + +func (p *PolicyStore) installRule(path []interface{}, rule *ast.Rule) error { + + err := p.dataStore.MakePath(path[:len(path)-1]) + if err != nil { + return errors.Wrapf(err, "unable to make path for rule set") + } + + node, err := p.dataStore.Get(path) + if err != nil { + switch err := err.(type) { + case *StorageError: + if err.Code == StorageNotFoundErr { + rules := []*ast.Rule{rule} + if err := p.dataStore.Patch(StorageAdd, path, rules); err != nil { + return errors.Wrapf(err, "unable to add new rule set") + } + return nil + } + } + return err + } + + rs, ok := node.([]*ast.Rule) + if !ok { + return fmt.Errorf("unable to add rule to base document") + } + + for i := range rs { + if rs[i].Equal(rule) { + return nil + } + } + + rs = append(rs, rule) + + if err := p.dataStore.Patch(StorageReplace, path, rs); err != nil { + return errors.Wrapf(err, "unable to add rule to existing rule set") + } + + return nil +} + +func (p *PolicyStore) uninstallModule(mod *ast.Module) error { + uninstalled := map[*ast.Rule][]interface{}{} + for _, r := range mod.Rules { + fqn := append(ast.Ref{}, mod.Package.Path...) + fqn = append(fqn, &ast.Term{Value: ast.String(r.Name)}) + path, _ := fqn.Underlying() + path = path[1:] + if err := p.uninstallRule(path, r); err != nil { + for r, path := range uninstalled { + if err := p.installRule(path, r); err != nil { + return err + } + } + return err + } + uninstalled[r] = path + } + return nil +} + +// uninstallRule removes the rule located at the path. If the path is not found +// or the rule does not exist in the ruleset, this function returns nil (no error). +func (p *PolicyStore) uninstallRule(path []interface{}, rule *ast.Rule) error { + + node, err := p.dataStore.Get(path) + + if IsStorageNotFound(err) { + return nil + } + + rs, ok := node.([]*ast.Rule) + if !ok { + return fmt.Errorf("unable to remove rule: path refers to base document") + } + + found := false + + for i := range rs { + if rs[i].Equal(rule) { + rs = append(rs[:i], rs[i+1:]...) + found = true + break + } + } + + if !found { + return nil + } + + if len(rs) == 0 { + return p.dataStore.Patch(StorageRemove, path, nil) + } + + return p.dataStore.Patch(StorageReplace, path, rs) +} diff --git a/eval/policystore_test.go b/eval/policystore_test.go new file mode 100644 index 0000000000..b627dadf1d --- /dev/null +++ b/eval/policystore_test.go @@ -0,0 +1,305 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package eval + +import ( + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/open-policy-agent/opa/ast" +) + +func TestPolicyStoreDefaultOpen(t *testing.T) { + + dir, err := ioutil.TempDir("", "policyDir") + if err != nil { + panic(err) + } + + defer os.RemoveAll(dir) + + filename := filepath.Join(dir, "testMod1") + + err = ioutil.WriteFile(filename, []byte(testMod1), 0644) + if err != nil { + panic(err) + } + + dataStore := NewStorage() + policyStore := NewPolicyStore(dataStore, dir) + + err = policyStore.Open(LoadPolicies) + if err != nil { + t.Errorf("Unexpected error on Open(): %v", err) + return + } + + c := ast.NewCompiler() + mod := ast.MustParseModule(testMod1) + if c.Compile(map[string]*ast.Module{"testMod1": mod}); c.Failed() { + panic(c.FlattenErrors()) + } + + stored, err := policyStore.Get("testMod1") + if err != nil { + t.Errorf("Unexpected error on Get(): %v", err) + return + } + + if !c.Modules["testMod1"].Equal(stored) { + t.Errorf("Expected %v from policy store but got: %v", c.Modules["testMod1"], stored) + return + } +} + +func TestPolicyStoreAdd(t *testing.T) { + + f := newFixture() + defer f.cleanup() + + mod1 := f.compile1(testMod1) + mod2 := f.compile1(testMod2) + + err := f.policyStore.Add("testMod1", mod1, []byte(testMod1), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + err = f.policyStore.Add("testMod2", mod2, []byte(testMod2), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + r, err := f.policyStore.Get("testMod1") + if err != nil { + t.Errorf("Unexpected error on Get(): %v", err) + return + } + + if !mod1.Equal(r) { + t.Errorf("Expected %v for Get() but got: %v", mod1, r) + return + } + + raw, err := f.policyStore.GetRaw("testMod1") + if err != nil { + t.Errorf("Unexpected error on GetRaw(): %v", err) + return + } + + if string(raw) != testMod1 { + t.Errorf("Expected %v for GetRaw() but got: %v", testMod1, raw) + } + + mods := f.policyStore.List() + + if len(mods) != 2 { + t.Errorf("Expected a single module from List() but got: %v", mods) + return + } + + if !mods["testMod1"].Equal(mod1) { + t.Errorf("Expected List() result to equal %v but got %v", mod1, mods["testMod1"]) + return + } +} + +func TestPolicyStoreAddIdempotent(t *testing.T) { + + f := newFixture() + defer f.cleanup() + + mod1 := f.compile1(testMod1) + + err := f.policyStore.Add("testMod1", mod1, []byte(testMod1), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + err = f.policyStore.Add("testMod1", mod1, []byte(testMod1), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + node, err := f.dataStore.Get(path("a.b.p")) + if err != nil { + t.Errorf("Unexpected error on Get(): %v", err) + return + } + + rules := node.([]*ast.Rule) + if len(rules) != 1 { + t.Errorf("Expected ruleset to exactly one rule: %v", rules) + return + } + + if !rules[0].Equal(mod1.Rules[0]) { + t.Errorf("Expected rule to be %v but got: %v", mod1, rules[0]) + return + } +} + +func TestPolicyStoreRemove(t *testing.T) { + + f := newFixture() + defer f.cleanup() + + mod1 := f.compile1(testMod1) + mod2 := f.compile1(testMod2) + + err := f.policyStore.Add("testMod1", mod1, []byte(testMod1), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + err = f.policyStore.Add("testMod2", mod2, []byte(testMod2), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + if err := f.policyStore.Remove("testMod1"); err != nil { + t.Errorf("Unexpected error on Remove(): %v", err) + return + } + + mods := f.policyStore.List() + + if len(mods) != 1 { + t.Errorf("Expected one module to remain after Remove(): %v", mods) + return + } + + if _, err := f.policyStore.Get("testMod2"); err != nil { + t.Errorf("Expected testMod2 to remain after Remove(): %v", mods) + return + } + + _, err = os.Stat(f.policyStore.getFilename("testMod1")) + if !os.IsNotExist(err) { + info, err := ioutil.ReadDir(f.policyStore.policyDir) + if err != nil { + panic(err) + } + files := []string{} + for _, i := range info { + files = append(files, i.Name()) + } + t.Errorf("Expected testMod1 to be removed from disk but %v contains: %v", f.policyStore.policyDir, files) + return + } +} + +func TestPolicyStoreUpdate(t *testing.T) { + f := newFixture() + defer f.cleanup() + + mod1 := f.compile1(testMod1) + mod2 := f.compile1(testMod2) + + err := f.policyStore.Add("testMod1", mod1, []byte(testMod1), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + err = f.policyStore.Add("testMod1", mod2, []byte(testMod2), true) + if err != nil { + t.Errorf("Unexpected error on Add(): %v", err) + return + } + + node, err := f.dataStore.Get(path("a.b.p")) + if err != nil { + t.Errorf("Unexpected error on Get(): %v", err) + return + } + + rules := node.([]*ast.Rule) + if len(rules) != 1 { + t.Errorf("Expected exactly one rule but got: %v", rules) + return + } + + if !rules[0].Equal(mod2.Rules[0]) { + t.Errorf("Expected rule to equal %v but got: %v", mod2.Rules[0], rules[0]) + return + } + + node, err = f.dataStore.Get(path("a.b.q")) + if !IsStorageNotFound(err) { + t.Errorf("Expected storage not found error but got: %v (err: %v)", node, err) + return + } +} + +const ( + testMod1 = ` + package a.b + + p = true :- true + q = true :- true + ` + + testMod2 = ` + package a.b + + p = true :- false + ` +) + +type fixture struct { + policyStore *PolicyStore + dataStore *Storage +} + +func newFixture() *fixture { + + dir, err := ioutil.TempDir("", "policyDir") + if err != nil { + panic(err) + } + + dataStore := NewStorage() + policyStore := NewPolicyStore(dataStore, dir) + err = policyStore.Open(func(map[string][]byte) (map[string]*ast.Module, error) { + return nil, nil + }) + if err != nil { + panic(err) + } + + f := &fixture{ + policyStore: policyStore, + dataStore: dataStore, + } + + return f +} + +func (f *fixture) cleanup() { + os.RemoveAll(f.policyStore.policyDir) +} + +func (f *fixture) compile1(m string) *ast.Module { + + mods := f.policyStore.List() + mod := ast.MustParseModule(m) + mods[""] = mod + + c := ast.NewCompiler() + if c.Compile(mods); c.Failed() { + panic(c.FlattenErrors()) + } + + return c.Modules[""] +} diff --git a/eval/storage.go b/eval/storage.go index 9ab7809f40..a75ba58c7e 100644 --- a/eval/storage.go +++ b/eval/storage.go @@ -5,12 +5,9 @@ package eval import ( - "encoding/json" "fmt" - "os" "github.com/open-policy-agent/opa/ast" - "github.com/pkg/errors" ) // StorageErrorCode represents the collection of error types that can be @@ -36,6 +33,15 @@ func (err *StorageError) Error() string { return fmt.Sprintf("storage error (code: %d): %v", err.Code, err.Message) } +// IsStorageNotFound returns true if this error is a StorageNotFoundErr +func IsStorageNotFound(err error) bool { + switch err := err.(type) { + case *StorageError: + return err.Code == StorageNotFoundErr + } + return false +} + var doesNotExistMsg = "document does not exist" var outOfRangeMsg = "array index out of range" var nonEmptyMsg = "path must be non-empty" @@ -62,6 +68,11 @@ func notFoundError(path []interface{}, f string, a ...interface{}) *StorageError if len(f) > 0 { msg += ", " + fmt.Sprintf(f, a...) } + return notFoundErrorf(msg) +} + +func notFoundErrorf(f string, a ...interface{}) *StorageError { + msg := fmt.Sprintf(f, a...) return &StorageError{ Code: StorageNotFoundErr, Message: msg, @@ -74,110 +85,18 @@ type Storage struct { data map[string]interface{} } -// NewEmptyStorage is a helper for creating a new, empty Storage. -func NewEmptyStorage() *Storage { +// NewStorage is a helper for creating a new, empty Storage. +func NewStorage() *Storage { return &Storage{ Indices: NewIndices(), data: map[string]interface{}{}, } } -// NewStorage is a helper for creating a new Storage containing -// the given base documents and rules. -func NewStorage(docs []map[string]interface{}, mods map[string]*ast.Module) (*Storage, error) { - - store := NewEmptyStorage() - - for _, d := range docs { - // TODO(tsandall): recursive merge instead of replace? - for k, v := range d { - if err := store.Patch(StorageAdd, []interface{}{k}, v); err != nil { - return nil, err - } - } - } - - for _, m := range mods { - - for _, r := range m.Rules { - - fqn := append(ast.Ref{}, m.Package.Path...) - fqn = append(fqn, &ast.Term{Value: ast.String(r.Name)}) - - path, _ := fqn.Underlying() - path = path[1:] - - err := store.MakePath(path[:len(path)-1]) - if err != nil { - return nil, errors.Wrapf(err, "unable to make path for rule set") - } - - node, err := store.Get(path) - if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - rules := []*ast.Rule{r} - if err := store.Patch(StorageAdd, path, rules); err != nil { - return nil, errors.Wrapf(err, "unable to add new rule set") - } - continue - } - } - return nil, err - } - - rs, ok := node.([]*ast.Rule) - if !ok { - return nil, fmt.Errorf("unable to add rule to base document") - } - - rs = append(rs, r) - - if err := store.Patch(StorageReplace, path, rs); err != nil { - return nil, errors.Wrapf(err, "unable to add rule to existing rule set") - } - } - } - - return store, nil -} - -// NewStorageFromFiles is a helper for creating a new Storage containing -// documents stored in files and/or policy modules. -func NewStorageFromFiles(files []string) (*Storage, error) { - - modules := map[string]*ast.Module{} - docs := []map[string]interface{}{} - - for _, file := range files { - m, astErr := ast.ParseModuleFile(file) - if astErr == nil { - modules[file] = m - continue - } - d, jsonErr := parseJSONObjectFile(file) - if jsonErr == nil { - docs = append(docs, d) - continue - } - // TODO(tsandall): add heuristic to determine whether this supposed - // to be a policy module or a JSON file. Format appropriate error. - return nil, fmt.Errorf("parse error: %v: %v: %v", file, astErr, jsonErr) - } - - c := ast.NewCompiler() - c.Compile(modules) - if c.Failed() { - return nil, fmt.Errorf(c.FlattenErrors()) - } - - return NewStorage(docs, c.Modules) -} - // NewStorageFromJSONObject returns Storage by converting from map[string]interface{} +// This is mostly for test purposes. func NewStorageFromJSONObject(data map[string]interface{}) *Storage { - store := NewEmptyStorage() + store := NewStorage() for k, v := range data { if err := store.Patch(StorageAdd, []interface{}{k}, v); err != nil { panic(err) @@ -661,17 +580,3 @@ func checkArrayIndex(path []interface{}, node []interface{}, v interface{}) (int } return i, nil } - -func parseJSONObjectFile(file string) (map[string]interface{}, error) { - f, err := os.Open(file) - if err != nil { - return nil, err - } - defer f.Close() - reader := json.NewDecoder(f) - var data map[string]interface{} - if err := reader.Decode(&data); err != nil { - return nil, err - } - return data, nil -} diff --git a/eval/storage_test.go b/eval/storage_test.go index 6498528a5f..1d9b6e5af1 100644 --- a/eval/storage_test.go +++ b/eval/storage_test.go @@ -7,70 +7,12 @@ package eval import ( "encoding/json" "fmt" - "io/ioutil" - "os" "reflect" "testing" "github.com/open-policy-agent/opa/ast" ) -func TestLoadFromFiles(t *testing.T) { - tmp1, err := ioutil.TempFile("", "docFile") - if err != nil { - panic(err) - } - defer os.Remove(tmp1.Name()) - doc1 := `{"foo": "bar", "a": {"b": {"d": [1]}}}` - if _, err := tmp1.Write([]byte(doc1)); err != nil { - panic(err) - } - if err := tmp1.Close(); err != nil { - panic(err) - } - - tmp2, err := ioutil.TempFile("", "policyFile") - if err != nil { - panic(err) - } - defer os.Remove(tmp2.Name()) - mod1 := ` - package a.b.c - import data.foo - p = true :- foo = "bar" - p = true :- 1 = 2 - ` - if _, err := tmp2.Write([]byte(mod1)); err != nil { - panic(err) - } - if err := tmp2.Close(); err != nil { - panic(err) - } - - store, err := NewStorageFromFiles([]string{tmp1.Name(), tmp2.Name()}) - if err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - - r, err := store.Get(path("foo")) - if Compare(r, "bar") != 0 || err != nil { - t.Errorf("Expected %v but got %v (err: %v)", "bar", r, err) - return - } - - r, err = store.Get(path("a.b.c.p")) - rules, ok := r.([]*ast.Rule) - if !ok { - t.Errorf("Expected rules but got: %v", r) - return - } - if !rules[0].Name.Equal(ast.Var("p")) { - t.Errorf("Expected rule p but got: %v", rules[0]) - return - } -} - func TestStorageGet(t *testing.T) { data := loadSmallTestData() diff --git a/eval/topdown.go b/eval/topdown.go index c5b925e625..d7fd26b907 100644 --- a/eval/topdown.go +++ b/eval/topdown.go @@ -660,11 +660,8 @@ func evalRefRecEnumColl(ctx *TopDownContext, path, tail ast.Ref, iter TopDownIte node, err := lookup(ctx.Store, path) if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - return nil - } + if IsStorageNotFound(err) { + return nil } return err } @@ -715,11 +712,8 @@ func evalRefRecGround(ctx *TopDownContext, path, tail ast.Ref, iter TopDownItera path = append(path, tail[0]) node, err := lookupRule(ctx.Store, path) if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - return nil - } + if IsStorageNotFound(err) { + return nil } return err } @@ -1221,11 +1215,8 @@ func lookup(store *Storage, ref ast.Ref) (interface{}, error) { func lookupExists(store *Storage, ref ast.Ref) (bool, error) { _, err := lookup(store, ref) if err != nil { - switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - return false, nil - } + if IsStorageNotFound(err) { + return false, nil } return false, err } diff --git a/eval/topdown_test.go b/eval/topdown_test.go index 7de14e4e5c..627c7d59b7 100644 --- a/eval/topdown_test.go +++ b/eval/topdown_test.go @@ -525,9 +525,15 @@ func TestTopDownEmbeddedVirtualDoc(t *testing.T) { q[x] :- g[j][k] = x`}) data := loadSmallTestData() - store, err := NewStorage([]map[string]interface{}{data}, mods) - if err != nil { - panic(err) + + store := NewStorageFromJSONObject(data) + policyStore := NewPolicyStore(store, "") + + for id, mod := range mods { + err := policyStore.Add(id, mod, []byte(""), false) + if err != nil { + panic(err) + } } assertTopDown(t, store, 0, "deep embedded vdoc", []string{"b", "c", "d", "p"}, "[1, 2, 4]") @@ -583,9 +589,14 @@ func TestExample(t *testing.T) { mods := compileModules([]string{vd}) - store, err := NewStorage([]map[string]interface{}{doc}, mods) - if err != nil { - panic(err) + store := NewStorageFromJSONObject(doc) + policyStore := NewPolicyStore(store, "") + + for id, mod := range mods { + err := policyStore.Add(id, mod, []byte(""), false) + if err != nil { + panic(err) + } } assertTopDown(t, store, 0, "public servers", []string{"opa", "example", "public_servers"}, ` @@ -629,7 +640,7 @@ func compileRules(imports []string, input []string) map[string]*ast.Module { is := []*ast.Import{} for _, i := range imports { is = append(is, &ast.Import{ - Path: ast.MustParseRef(i), + Path: ast.MustParseTerm(i), }) } @@ -757,10 +768,19 @@ func runTopDownTestCase(t *testing.T, data map[string]interface{}, i int, note s for k := range data { imports = append(imports, "data."+k) } - store, err := NewStorage([]map[string]interface{}{data}, compileRules(imports, rules)) - if err != nil { - panic(err) + + mods := compileRules(imports, rules) + + store := NewStorageFromJSONObject(data) + policyStore := NewPolicyStore(store, "") + + for id, mod := range mods { + err := policyStore.Add(id, mod, []byte(""), false) + if err != nil { + panic(err) + } } + assertTopDown(t, store, i, note, []string{"p"}, expected) } diff --git a/eval/tracer_test.go b/eval/tracer_test.go index 435069c73d..ee2cdb2804 100644 --- a/eval/tracer_test.go +++ b/eval/tracer_test.go @@ -21,14 +21,21 @@ func (t *mockTracer) Trace(ctx *TopDownContext, f string, a ...interface{}) { func TestTracer(t *testing.T) { + data := loadSmallTestData() + mods := compileRules([]string{"data.a"}, []string{ "p[x] :- q[x] = y", "q[i] = j :- a[i] = j", }) - store, err := NewStorage([]map[string]interface{}{loadSmallTestData()}, mods) - if err != nil { - panic(err) + store := NewStorageFromJSONObject(data) + policyStore := NewPolicyStore(store, "") + + for id, mod := range mods { + err := policyStore.Add(id, mod, []byte(""), false) + if err != nil { + panic(err) + } } tracer := &mockTracer{[]string{}} diff --git a/runtime/repl.go b/runtime/repl.go index 5b9dac0764..20a4c457bc 100644 --- a/runtime/repl.go +++ b/runtime/repl.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "math/rand" "os" "sort" "strings" @@ -33,6 +32,7 @@ type Repl struct { InitPrompt string BufferPrompt string Buffer []string + nextID int } // NewRepl creates a new Repl. @@ -157,8 +157,10 @@ func (r *Repl) cmdTrace() bool { } func (r *Repl) compileBody(body ast.Body) (ast.Body, error) { + name := fmt.Sprintf("repl%d", r.nextID) + r.nextID++ rule := &ast.Rule{ - Name: ast.Var(randString(32)), + Name: ast.Var(name), Body: body, } // TODO(tsandall): refactor to use current implicit module @@ -170,11 +172,11 @@ func (r *Repl) compileBody(body ast.Body) (ast.Body, error) { Rules: []*ast.Rule{rule}, } c := ast.NewCompiler() - c.Compile(map[string]*ast.Module{"tmp": m}) + c.Compile(map[string]*ast.Module{name: m}) if len(c.Errors) > 0 { return nil, fmt.Errorf(c.FlattenErrors()) } - return c.Modules["tmp"].Rules[0].Body, nil + return c.Modules[name].Rules[0].Body, nil } func (r *Repl) compileRule(rule *ast.Rule) (*ast.Rule, error) { @@ -455,14 +457,3 @@ func buildHeader(fields map[string]struct{}, term *ast.Term) { } } } - -// randString returns a random string of letters. -// http://stackoverflow.com/a/31832326 -func randString(length int) string { - letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") - s := make([]rune, length) - for i := range s { - s[i] = letters[rand.Intn(len(letters))] - } - return string(s) -} diff --git a/runtime/runtime.go b/runtime/runtime.go index e378f69848..fb66d2f0a5 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -5,50 +5,217 @@ package runtime import ( + "encoding/json" "fmt" + "io/ioutil" "os" + "path/filepath" + "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/eval" + "github.com/pkg/errors" ) // Params stores the configuration for an OPA instance. type Params struct { - Server bool - Paths []string + + // Addr is the listening address that the OPA server will bind to. + Addr string + + // Server flag controls whether the OPA instance will start a server. + // By default, the OPA instance acts as an interactive shell. + Server bool + + // Paths contains filenames of base documents and policy modules to + // load on startup. + Paths []string + + // HistoryPath is the filename to store the interactive shell user + // input history. HistoryPath string + + // PolicyDir is the filename of the directory to persist policy + // definitions in. Policy definitions stored in this directory + // are automatically loaded on startup. + PolicyDir string } // Runtime represents a single OPA instance. type Runtime struct { - Store *eval.Storage + Store *eval.Storage + PolicyStore *eval.PolicyStore } -// Start is the entry point of an OPA instance. -func (rt *Runtime) Start(params *Params) { +// Init initializes the OPA instance. +func (rt *Runtime) Init(params *Params) error { - store, err := eval.NewStorageFromFiles(params.Paths) + if len(params.PolicyDir) > 0 { + if err := os.MkdirAll(params.PolicyDir, 0755); err != nil { + return errors.Wrap(err, "unable to make --policy-dir") + } + } + parsed, err := parseInputs(params.Paths) if err != nil { - fmt.Println("failed to open storage:", err) - os.Exit(1) + return errors.Wrapf(err, "parse error") + } + + // Open data store and load base documents. + dataStore := eval.NewStorage() + + for _, doc := range parsed.docs { + for k, v := range doc { + if err := dataStore.Patch(eval.StorageAdd, []interface{}{k}, v); err != nil { + return errors.Wrap(err, "unable to open data store") + } + } + } + + // Open policy store and load existing policies. + policyStore := eval.NewPolicyStore(dataStore, params.PolicyDir) + if err := policyStore.Open(eval.LoadPolicies); err != nil { + return errors.Wrap(err, "unable to open policy store") + } + + // Load policies provided via input. + if err := compileAndStoreInputs(parsed.modules, policyStore); err != nil { + return errors.Wrapf(err, "compile error") } - rt.Store = store + rt.PolicyStore = policyStore + rt.Store = dataStore + + return nil +} + +// Start is the entry point of an OPA instance. +func (rt *Runtime) Start(params *Params) { + + if err := rt.Init(params); err != nil { + fmt.Println("error initializing runtime:", err) + os.Exit(1) + } if !params.Server { - rt.runRepl(params) + rt.startRepl(params) } else { - rt.runServer(params) + rt.startServer(params) } } -func (rt *Runtime) runServer(params *Params) { - fmt.Println("not implemented: server mode") - os.Exit(1) +func (rt *Runtime) startServer(params *Params) { + persist := len(params.PolicyDir) > 0 + server := NewServer(rt, params.Addr, persist) + server.Loop() } -func (rt *Runtime) runRepl(params *Params) { - +func (rt *Runtime) startRepl(params *Params) { repl := NewRepl(rt, params.HistoryPath, os.Stdout) repl.Loop() } + +func compileAndStoreInputs(parsed map[string]*parsedModule, policyStore *eval.PolicyStore) error { + + mods := policyStore.List() + for _, p := range parsed { + mods[p.id] = p.mod + } + + c := ast.NewCompiler() + if c.Compile(mods); c.Failed() { + // TODO(tsandall): add another call on compiler to flatten into error type + return c.Errors[0] + } + + for id := range parsed { + mod := c.Modules[id] + if err := policyStore.Add(id, mod, parsed[id].raw, false); err != nil { + return err + } + } + + return nil +} + +type parsedModule struct { + id string + mod *ast.Module + raw []byte +} + +type parsedInput struct { + docs []map[string]interface{} + modules map[string]*parsedModule +} + +func parseInputs(paths []string) (*parsedInput, error) { + + parsedDocs := []map[string]interface{}{} + parsedModules := map[string]*parsedModule{} + + for _, file := range paths { + + info, err := os.Stat(file) + if err != nil { + return nil, err + } + + if info.IsDir() { + continue + } + + bs, err := ioutil.ReadFile(file) + + if err != nil { + return nil, err + } + + m, astErr := ast.ParseModuleFile(file) + + if astErr == nil { + parsedModules[file] = &parsedModule{ + id: file, + mod: m, + raw: bs, + } + continue + } + + d, jsonErr := parseJSONObjectFile(file) + + if jsonErr == nil { + parsedDocs = append(parsedDocs, d) + continue + } + + switch filepath.Ext(file) { + case ".json": + return nil, jsonErr + case ".rego": + return nil, astErr + default: + return nil, fmt.Errorf("unrecognizable file: %v", file) + } + } + + r := &parsedInput{ + docs: parsedDocs, + modules: parsedModules, + } + + return r, nil +} + +func parseJSONObjectFile(file string) (map[string]interface{}, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + reader := json.NewDecoder(f) + var data map[string]interface{} + if err := reader.Decode(&data); err != nil { + return nil, err + } + return data, nil +} diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go new file mode 100644 index 0000000000..2fed36a4a4 --- /dev/null +++ b/runtime/runtime_test.go @@ -0,0 +1,125 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package runtime + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/eval" +) + +func TestInit(t *testing.T) { + tmp1, err := ioutil.TempFile("", "docFile") + if err != nil { + panic(err) + } + defer os.Remove(tmp1.Name()) + doc1 := `{"foo": "bar", "a": {"b": {"d": [1]}}}` + if _, err := tmp1.Write([]byte(doc1)); err != nil { + panic(err) + } + if err := tmp1.Close(); err != nil { + panic(err) + } + + tmp2, err := ioutil.TempFile("", "policyFile") + if err != nil { + panic(err) + } + defer os.Remove(tmp2.Name()) + mod1 := ` + package a.b.c + import data.foo + p = true :- foo = "bar" + p = true :- 1 = 2 + ` + if _, err := tmp2.Write([]byte(mod1)); err != nil { + panic(err) + } + if err := tmp2.Close(); err != nil { + panic(err) + } + + tmp3, err := ioutil.TempDir("", "policyDir") + if err != nil { + panic(err) + } + + defer os.RemoveAll(tmp3) + + tmp4 := filepath.Join(tmp3, "existingPolicy") + + err = ioutil.WriteFile(tmp4, []byte(` + package a.b.c + q = true :- p + `), 0644) + if err != nil { + panic(err) + } + + rt := Runtime{} + + err = rt.Init(&Params{ + Paths: []string{tmp1.Name(), tmp2.Name()}, + PolicyDir: tmp3, + }) + + if err != nil { + t.Errorf("Unexpected error: %v", err) + return + } + + node, err := rt.Store.Get(path("foo")) + if eval.Compare(node, "bar") != 0 || err != nil { + t.Errorf("Expected %v but got %v (err: %v)", "bar", node, err) + return + } + + node, err = rt.Store.Get(path("a.b.c.p")) + rules, ok := node.([]*ast.Rule) + if !ok { + t.Errorf("Expected rules but got: %v", node) + return + } + if !rules[0].Name.Equal(ast.Var("p")) { + t.Errorf("Expected rule p but got: %v", rules[0]) + return + } + + node, err = rt.Store.Get(path("a.b.c.q")) + rules, ok = node.([]*ast.Rule) + if !ok { + t.Errorf("Expected rules but got: %v", node) + return + } + if !rules[0].Name.Equal(ast.Var("q")) { + t.Errorf("Expected rule q but got: %v", rules[0]) + return + } +} + +func path(input interface{}) []interface{} { + switch input := input.(type) { + case []interface{}: + return input + case string: + switch v := ast.MustParseTerm(input).Value.(type) { + case ast.Var: + return []interface{}{string(v)} + case ast.Ref: + path, err := v.Underlying() + if err != nil { + panic(err) + } + return path + } + } + panic(fmt.Sprintf("illegal value: %v", input)) +} diff --git a/runtime/server.go b/runtime/server.go new file mode 100644 index 0000000000..1b36686d40 --- /dev/null +++ b/runtime/server.go @@ -0,0 +1,538 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package runtime + +import ( + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" + "strings" + "sync" + "time" + + "github.com/gorilla/mux" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/version" + "github.com/pkg/errors" +) + +// apiErrorV1 models an error response sent to the client. +type apiErrorV1 struct { + Code int + Message string +} + +func (err *apiErrorV1) Bytes() []byte { + if bs, err := json.MarshalIndent(err, "", " "); err == nil { + return bs + } + return nil +} + +// patchV1 models a single patch operation against a document. +type patchV1 struct { + Op string `json:"op"` + Path string `json:"path"` + Value interface{} `json:"value"` +} + +// policyV1 models a policy module in OPA. +type policyV1 struct { + ID string + Module *ast.Module +} + +func (p *policyV1) Equal(other *policyV1) bool { + return p.ID == other.ID && p.Module.Equal(other.Module) +} + +// resultSetV1 models the result of an ad-hoc query. +type resultSetV1 []map[string]interface{} + +// Server contains runtime state specific to the server-mode persona, e.g., +// HTTP router. +// +// Notes: +// +// - In the future, the HTTP routing could be factored into a separate module +// relying on the server (which would remain RPC-based). For now, it's simpler +// to keep the HTTP routing and backend implementation in one place. +type Server struct { + Addr string + Persist bool + Runtime *Runtime + Router *mux.Router + + mtx sync.RWMutex +} + +// NewServer returns a new Server. +func NewServer(rt *Runtime, addr string, persist bool) *Server { + + s := &Server{ + Addr: addr, + Persist: persist, + Runtime: rt, + Router: mux.NewRouter(), + } + + s.registerHandlerV1("/data/{path:.+}", "GET", s.v1DataGet) + s.registerHandlerV1("/data/{path:.+}", "PATCH", s.v1DataPatch) + s.registerHandlerV1("/policies", "GET", s.v1PoliciesList) + s.registerHandlerV1("/policies/{id}", "DELETE", s.v1PoliciesDelete) + s.registerHandlerV1("/policies/{id}", "GET", s.v1PoliciesGet) + s.registerHandlerV1("/policies/{id}/raw", "GET", s.v1PoliciesRawGet) + s.registerHandlerV1("/policies/{id}", "PUT", s.v1PoliciesPut) + s.registerHandlerV1("/query", "GET", s.v1QueryGet) + + s.Router.HandleFunc("/", s.indexGet).Methods("GET") + + return s +} + +// Loop starts the server. This function does not return. +func (s *Server) Loop() { + http.ListenAndServe(s.Addr, s.Router) +} + +func (s *Server) execQuery(qStr string) (resultSetV1, error) { + + query, err := ast.ParseBody(qStr) + + if err != nil { + return nil, err + } + + path := ast.Ref{ast.DefaultRootDocument} + + rule := &ast.Rule{ + Body: query, + } + + mod := &ast.Module{ + Package: &ast.Package{ + Path: path, + }, + Rules: []*ast.Rule{rule}, + } + + c := ast.NewCompiler() + + if c.Compile(map[string]*ast.Module{"": mod}); c.Failed() { + return nil, c.Errors[0] + } + + compiled := c.Modules[""].Rules[0].Body + + ctx := eval.NewTopDownContext(compiled, s.Runtime.Store) + + results := resultSetV1{} + + s.mtx.RLock() + defer s.mtx.RUnlock() + + err = eval.TopDown(ctx, func(ctx *eval.TopDownContext) error { + result := map[string]interface{}{} + var err error + ctx.Bindings.Iter(func(k, v ast.Value) bool { + kv, ok := k.(ast.Var) + if !ok { + return false + } + vv, e := eval.ValueToInterface(v, ctx) + if err != nil { + err = e + return true + } + result[string(kv)] = vv + return false + }) + if err != nil { + return err + } + if len(result) > 0 { + results = append(results, result) + } + return nil + }) + + return results, err +} + +func (s *Server) indexGet(w http.ResponseWriter, r *http.Request) { + + renderHeader(w) + renderBanner(w) + renderVersion(w) + + values := r.URL.Query() + qStrs := values["q"] + + renderQueryForm(w, qStrs) + + if len(qStrs) > 0 { + qStr := qStrs[len(qStrs)-1] + t0 := time.Now() + results, err := s.execQuery(qStr) + dt := time.Since(t0) + renderQueryResult(w, results, err, dt) + } + + renderFooter(w) +} + +func (s *Server) registerHandlerV1(path string, method string, h func(http.ResponseWriter, *http.Request)) { + s.Router.HandleFunc("/v1"+path, h).Methods(method) +} + +func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + path := strings.Split(vars["path"], "/") + params := &eval.TopDownQueryParams{ + Store: s.Runtime.Store, + Path: path, + } + + s.mtx.RLock() + defer s.mtx.RUnlock() + + result, err := eval.TopDownQuery(params) + + if err != nil { + handleErrorAuto(w, err) + return + } + + handleResponseJSON(w, 200, result) +} + +func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + root := strings.Split(vars["path"], "/") + + ops := []patchV1{} + if err := json.NewDecoder(r.Body).Decode(&ops); err != nil { + handleError(w, 400, err) + return + } + + path := []interface{}{} + for _, x := range root { + path = append(path, x) + } + + s.mtx.Lock() + defer s.mtx.Unlock() + + for i := range ops { + + var op eval.StorageOp + + // TODO this could be refactored for failure handling + switch ops[i].Op { + case "add": + op = eval.StorageAdd + case "remove": + op = eval.StorageRemove + case "replace": + op = eval.StorageReplace + default: + handleErrorf(w, 400, "bad patch operation: %v", ops[i].Op) + return + } + + parts := strings.Split(ops[i].Path[1:], "/") + + for _, x := range parts { + if x == "" { + continue + } + path = append(path, x) + } + + if err := s.Runtime.Store.Patch(op, path, ops[i].Value); err != nil { + handleErrorAuto(w, err) + return + } + + path = path[:len(root)] + } + + handleResponse(w, 204, nil) +} + +func (s *Server) v1PoliciesDelete(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id := vars["id"] + + _, err := s.Runtime.PolicyStore.Get(id) + if err != nil { + handleErrorAuto(w, err) + return + } + + s.mtx.Lock() + defer s.mtx.Unlock() + + mods := s.Runtime.PolicyStore.List() + delete(mods, id) + + c := ast.NewCompiler() + if c.Compile(mods); c.Failed() { + handleErrorf(w, 400, c.FlattenErrors()) + return + } + + if err := s.Runtime.PolicyStore.Remove(id); err != nil { + handleErrorAuto(w, err) + return + } + + handleResponse(w, 204, nil) +} + +func (s *Server) v1PoliciesGet(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id := vars["id"] + + s.mtx.RLock() + defer s.mtx.RUnlock() + + mod, err := s.Runtime.PolicyStore.Get(id) + if err != nil { + handleErrorAuto(w, err) + return + } + + policy := &policyV1{ + ID: id, + Module: mod, + } + + handleResponseJSONPretty(w, 200, policy) +} + +func (s *Server) v1PoliciesRawGet(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id := vars["id"] + + s.mtx.RLock() + defer s.mtx.RUnlock() + + bs, err := s.Runtime.PolicyStore.GetRaw(id) + + if err != nil { + handleErrorAuto(w, err) + return + } + + handleResponse(w, 200, bs) +} + +func (s *Server) v1PoliciesList(w http.ResponseWriter, r *http.Request) { + + policies := []*policyV1{} + + s.mtx.RLock() + defer s.mtx.RUnlock() + + for id, mod := range s.Runtime.PolicyStore.List() { + policy := &policyV1{ + ID: id, + Module: mod, + } + policies = append(policies, policy) + } + + handleResponseJSONPretty(w, 200, policies) +} + +func (s *Server) v1PoliciesPut(w http.ResponseWriter, r *http.Request) { + + vars := mux.Vars(r) + id := vars["id"] + + buf, err := ioutil.ReadAll(r.Body) + if err != nil { + handleError(w, 500, err) + return + } + + mod, err := ast.ParseModule(string(buf)) + if err != nil { + handleError(w, 400, err) + return + } + if mod == nil { + handleErrorf(w, 400, "refusing to add empty module") + return + } + + s.mtx.Lock() + defer s.mtx.Unlock() + + mods := s.Runtime.PolicyStore.List() + mods[id] = mod + + c := ast.NewCompiler() + + if c.Compile(mods); c.Failed() { + handleErrorf(w, 400, c.FlattenErrors()) + return + } + + mod = c.Modules[id] + + if err := s.Runtime.PolicyStore.Add(id, mod, buf, s.Persist); err != nil { + handleErrorAuto(w, err) + return + } + + policy := &policyV1{ + ID: id, + Module: mod, + } + + handleResponseJSONPretty(w, 200, policy) +} + +func (s *Server) v1QueryGet(w http.ResponseWriter, r *http.Request) { + values := r.URL.Query() + qStrs := values["q"] + if len(qStrs) == 0 { + handleErrorf(w, 400, "missing query parameter 'q'") + return + } + + qStr := qStrs[len(qStrs)-1] + results, err := s.execQuery(qStr) + + if err != nil { + handleErrorAuto(w, err) + return + } + + handleResponseJSON(w, 200, results) +} + +func handleError(w http.ResponseWriter, code int, err error) { + handleErrorf(w, code, err.Error()) +} + +func handleErrorAuto(w http.ResponseWriter, err error) { + var prev error + for curr := err; curr != prev; { + if eval.IsStorageNotFound(curr) { + handleError(w, 404, err) + return + } + prev = curr + curr = errors.Cause(prev) + } + handleError(w, 500, err) +} + +func handleErrorf(w http.ResponseWriter, code int, f string, a ...interface{}) { + headers := w.Header() + headers.Add("Content-Type", "application/json") + e := &apiErrorV1{Code: code, Message: fmt.Sprintf(f, a...)} + w.WriteHeader(code) + w.Write(e.Bytes()) +} + +func handleResponse(w http.ResponseWriter, code int, bs []byte) { + w.WriteHeader(code) + if code == 204 { + return + } + w.Write(bs) +} + +func handleResponseJSON(w http.ResponseWriter, code int, v interface{}) { + bs, err := json.Marshal(v) + if err != nil { + handleErrorAuto(w, err) + return + } + headers := w.Header() + headers.Add("Content-Type", "application/json") + handleResponse(w, code, bs) +} + +func handleResponseJSONPretty(w http.ResponseWriter, code int, v interface{}) { + bs, err := json.MarshalIndent(v, "", " ") + if err != nil { + handleErrorAuto(w, err) + return + } + headers := w.Header() + headers.Add("Content-Type", "application/json") + handleResponse(w, code, bs) +} + +func renderBanner(w http.ResponseWriter) { + fmt.Fprintln(w, `
+ ________      ________    ________
+|\   __  \    |\   __  \  |\   __  \
+\ \  \|\  \   \ \  \|\  \ \ \  \|\  \
+ \ \  \\\  \   \ \   ____\ \ \   __  \
+  \ \  \\\  \   \ \  \___|  \ \  \ \  \
+   \ \_______\   \ \__\      \ \__\ \__\
+    \|_______|    \|__|       \|__|\|__|
+	
`) + fmt.Fprintln(w, "Open Policy Agent - An open source project to policy enable any application.
") + fmt.Fprintln(w, "
") +} + +func renderFooter(w http.ResponseWriter) { + fmt.Fprintln(w, "") + fmt.Fprintln(w, "") +} + +func renderHeader(w http.ResponseWriter) { + fmt.Fprintln(w, "") + fmt.Fprintln(w, "") +} + +func renderQueryForm(w http.ResponseWriter, qStrs []string) { + + input := "" + + if len(qStrs) > 0 { + input = qStrs[len(qStrs)-1] + } + + fmt.Fprintf(w, ` +
+ Query:
+
+ +
`, input) +} + +func renderQueryResult(w io.Writer, results resultSetV1, err error, d time.Duration) { + + buf, err2 := json.MarshalIndent(results, "", " ") + + if err != nil { + fmt.Fprintf(w, "Query error (took %v):
%v
", d, err) + } else if err2 != nil { + fmt.Fprintf(w, "JSON marshal error:
%v
", err2) + } else { + fmt.Fprintf(w, "Query results (took %v):
", d) + fmt.Fprintf(w, "
%s
", string(buf)) + } +} + +func renderVersion(w http.ResponseWriter) { + fmt.Fprintln(w, "Version: "+version.Version+"
") + fmt.Fprintln(w, "Build Commit: "+version.Vcs+"
") + fmt.Fprintln(w, "Build Timestamp: "+version.Timestamp+"
") + fmt.Fprintln(w, "Build Hostname: "+version.Hostname+"
") + fmt.Fprintln(w, "
") +} diff --git a/runtime/server_test.go b/runtime/server_test.go new file mode 100644 index 0000000000..53710011f7 --- /dev/null +++ b/runtime/server_test.go @@ -0,0 +1,360 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package runtime + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + "os" + "reflect" + "strings" + "testing" + + "github.com/open-policy-agent/opa/ast" +) + +var policyDir string + +// TestMain creates a temporary direcotry for the server to +// save policies to. The directory name is stored in policyDir +// and is used by the newFixture function. +func TestMain(m *testing.M) { + d, err := ioutil.TempDir("", "server_test") + if err != nil { + panic(err) + } + defer os.RemoveAll(d) + policyDir = d + rc := m.Run() + os.Exit(rc) +} + +func TestDataPatchV1(t *testing.T) { + f := newFixture(t) + patch := newReqV1("PATCH", "/data/x", `[{"op": "add", "path": "/", "value": {"a": 1, "b": 2}}]`) + f.server.Router.ServeHTTP(f.recorder, patch) + + if f.recorder.Code != 204 { + t.Errorf("Expected success/no-content but got %v", f.recorder) + return + } + + get := newReqV1("GET", "/data/x/a", "") + f.reset() + f.server.Router.ServeHTTP(f.recorder, get) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + resp := f.loadResponse().(float64) + exp := float64(1) + if resp != exp { + t.Errorf("Expected %v but got: %v", exp, resp) + } +} + +func TestIndexGet(t *testing.T) { + f := newFixture(t) + get, err := http.NewRequest("GET", `/?q=foo = 1`, strings.NewReader("")) + if err != nil { + panic(err) + } + f.server.Router.ServeHTTP(f.recorder, get) + if f.recorder.Code != 200 { + t.Errorf("Expected success but got: %v", f.recorder) + return + } + page := f.recorder.Body.String() + if !strings.Contains(page, "Query result") { + t.Errorf("Expected page to contain 'Query result' but got: %v", page) + return + } +} + +func TestPoliciesPutV1(t *testing.T) { + f := newFixture(t) + req := newReqV1("PUT", "/policies/1", testMod) + + f.server.Router.ServeHTTP(f.recorder, req) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + policy := f.loadPolicy() + expected := newPolicy("1", testMod) + if !expected.Equal(policy) { + t.Errorf("Expected policies to be equal. Expected:\n\n%v\n\nGot:\n\n%v\n", expected, policy) + } +} + +func TestPoliciesPutV1Empty(t *testing.T) { + f := newFixture(t) + req := newReqV1("PUT", "/policies/1", "") + + f.server.Router.ServeHTTP(f.recorder, req) + + if f.recorder.Code != 400 { + t.Errorf("Expected bad request but got %v", f.recorder) + return + } +} + +func TestPoliciesPutV1ParseError(t *testing.T) { + f := newFixture(t) + req := newReqV1("PUT", "/policies/1", ` + package a.b.c + + p[x] %%^ ;- + `) + + f.server.Router.ServeHTTP(f.recorder, req) + + if f.recorder.Code != 400 { + t.Errorf("Expected bad request but got %v", f.recorder) + return + } +} + +// TODO(tsandall): revisit once safety checks are in place +func testPoliciesPutV1CompileError(t *testing.T) { + f := newFixture(t) + req := newReqV1("PUT", "/policies/1", ` + package a.b.c + p[x] :- q[x] + q[x] :- p[x] + `) + + f.server.Router.ServeHTTP(f.recorder, req) + + if f.recorder.Code != 400 { + t.Errorf("Expected bad request but got %v", f.recorder) + return + } +} + +func TestPoliciesListV1(t *testing.T) { + f := newFixture(t) + put := newReqV1("PUT", "/policies/1", testMod) + f.server.Router.ServeHTTP(f.recorder, put) + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + f.reset() + list := newReqV1("GET", "/policies", "") + + f.server.Router.ServeHTTP(f.recorder, list) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + var policies []*policyV1 + err := json.NewDecoder(f.recorder.Body).Decode(&policies) + if err != nil { + t.Errorf("Expected policy list but got error: %v", err) + return + } + + expected := []*policyV1{ + newPolicy("1", testMod), + } + if len(expected) != len(policies) { + t.Errorf("Expected %d policies but got: %v", len(expected), policies) + return + } + for i := range expected { + if !expected[i].Equal(policies[i]) { + t.Errorf("Expected policies to be equal. Expected:\n\n%v\n\nGot:\n\n%v\n", expected[i], policies[i]) + } + } +} + +func TestPoliciesGetV1(t *testing.T) { + f := newFixture(t) + put := newReqV1("PUT", "/policies/1", testMod) + f.server.Router.ServeHTTP(f.recorder, put) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + f.reset() + get := newReqV1("GET", "/policies/1", "") + + f.server.Router.ServeHTTP(f.recorder, get) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + policy := f.loadPolicy() + expected := newPolicy("1", testMod) + if !expected.Equal(policy) { + t.Errorf("Expected policies to be equal. Expected:\n\n%v\n\nGot:\n\n%v\n", expected, policy) + } +} + +func TestPoliciesGetRawV1(t *testing.T) { + f := newFixture(t) + put := newReqV1("PUT", "/policies/1", testMod) + f.server.Router.ServeHTTP(f.recorder, put) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + f.reset() + get := newReqV1("GET", "/policies/1/raw", "") + + f.server.Router.ServeHTTP(f.recorder, get) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + raw := f.recorder.Body.String() + if raw != testMod { + t.Errorf("Expected raw string to equal testMod:\n\nExpected:\n\n%v\n\nGot:\n\n%v\n", testMod, raw) + } + +} + +func TestPoliciesDeleteV1(t *testing.T) { + f := newFixture(t) + put := newReqV1("PUT", "/policies/1", testMod) + f.server.Router.ServeHTTP(f.recorder, put) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + f.reset() + del := newReqV1("DELETE", "/policies/1", "") + + f.server.Router.ServeHTTP(f.recorder, del) + + if f.recorder.Code != 204 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + f.reset() + get := newReqV1("GET", "/policies/1", "") + f.server.Router.ServeHTTP(f.recorder, get) + if f.recorder.Code != 404 { + t.Errorf("Expected not found but got %v", f.recorder) + return + } +} + +func TestQueryV1(t *testing.T) { + f := newFixture(t) + get := newReqV1("GET", `/query?q=a=[1,2,3],a[i]=x`, "") + f.server.Router.ServeHTTP(f.recorder, get) + + if f.recorder.Code != 200 { + t.Errorf("Expected success but got %v", f.recorder) + return + } + + var expected resultSetV1 + err := json.Unmarshal([]byte(`[{"a":[1,2,3],"i":0,"x":1},{"a":[1,2,3],"i":1,"x":2},{"a":[1,2,3],"i":2,"x":3}]`), &expected) + if err != nil { + panic(err) + } + + var result resultSetV1 + err = json.Unmarshal(f.recorder.Body.Bytes(), &result) + if err != nil { + t.Errorf("Unexpected error while unmarshalling result: %v", err) + return + } + + if !reflect.DeepEqual(result, expected) { + t.Errorf("Expected %v but got: %v", expected, result) + } +} + +const ( + testMod = ` + package a.b.c + import data.x.y as z + import data.p + q[x] :- p[x], not r[x] + r[x] :- z[x] = 4` +) + +type fixture struct { + runtime *Runtime + server *Server + recorder *httptest.ResponseRecorder + t *testing.T +} + +func newFixture(t *testing.T) *fixture { + runtime := &Runtime{} + runtime.Init(&Params{Server: true, PolicyDir: policyDir}) + server := NewServer(runtime, ":8182", false) + recorder := httptest.NewRecorder() + return &fixture{ + runtime: runtime, + server: server, + recorder: recorder, + t: t, + } +} + +func (f *fixture) loadPolicy() *policyV1 { + policy := &policyV1{} + err := json.NewDecoder(f.recorder.Body).Decode(policy) + if err != nil { + panic(err) + } + return policy +} + +func (f *fixture) loadResponse() interface{} { + var v interface{} + err := json.NewDecoder(f.recorder.Body).Decode(&v) + if err != nil { + panic(err) + } + return v +} + +func (f *fixture) reset() { + f.recorder = httptest.NewRecorder() +} + +func newPolicy(id, s string) *policyV1 { + compiler := ast.NewCompiler() + parsed := ast.MustParseModule(s) + if compiler.Compile(map[string]*ast.Module{"": parsed}); compiler.Failed() { + panic(compiler.FlattenErrors()) + } + mod := compiler.Modules[""] + return &policyV1{ID: id, Module: mod} +} + +func newReqV1(method string, path string, body string) *http.Request { + req, err := http.NewRequest(method, "/v1"+path, strings.NewReader(body)) + if err != nil { + panic(err) + } + return req +} From 3dc5a3ef336f232c83bcc9d3e3eea523f262dd21 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Fri, 13 May 2016 15:58:32 -0700 Subject: [PATCH 4/9] Move compare.go into util package --- eval/index.go | 3 ++- eval/topdown.go | 3 ++- eval/topdown_test.go | 3 ++- eval/tracer_test.go | 4 +++- {eval => util}/compare.go | 2 +- {eval => util}/compare_test.go | 2 +- 6 files changed, 11 insertions(+), 6 deletions(-) rename {eval => util}/compare.go (99%) rename {eval => util}/compare_test.go (99%) diff --git a/eval/index.go b/eval/index.go index 4160105bd0..07facc608d 100644 --- a/eval/index.go +++ b/eval/index.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/util" ) // Indices contains a mapping of non-ground references to values to sets of bindings. @@ -181,7 +182,7 @@ func (ind *Index) getNode(val interface{}) *indexNode { hashCode := hash(val) head := ind.table[hashCode] for entry := head; entry != nil; entry = entry.next { - if Compare(entry.key, val) == 0 { + if util.Compare(entry.key, val) == 0 { return entry } } diff --git a/eval/topdown.go b/eval/topdown.go index d7fd26b907..f416fa2f86 100644 --- a/eval/topdown.go +++ b/eval/topdown.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/util" "github.com/pkg/errors" ) @@ -356,7 +357,7 @@ func evalEqGround(ctx *TopDownContext, a ast.Value, b ast.Value, iter TopDownIte if err != nil { return err } - if Compare(av, bv) == 0 { + if util.Compare(av, bv) == 0 { return iter(ctx) } return nil diff --git a/eval/topdown_test.go b/eval/topdown_test.go index 627c7d59b7..57362d0795 100644 --- a/eval/topdown_test.go +++ b/eval/topdown_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/util" ) func TestEvalRef(t *testing.T) { @@ -824,7 +825,7 @@ type ResultSet []interface{} // Less returns true if the i'th index of resultSet is less than the j'th index. func (resultSet ResultSet) Less(i, j int) bool { - return Compare(resultSet[i], resultSet[j]) < 0 + return util.Compare(resultSet[i], resultSet[j]) < 0 } // Swap exchanges the i'th and j'th values in resultSet. diff --git a/eval/tracer_test.go b/eval/tracer_test.go index ee2cdb2804..39e41238f0 100644 --- a/eval/tracer_test.go +++ b/eval/tracer_test.go @@ -7,6 +7,8 @@ package eval import ( "fmt" "testing" + + "github.com/open-policy-agent/opa/util" ) type mockTracer struct { @@ -53,7 +55,7 @@ func TestTracer(t *testing.T) { expected := []interface{}{float64(0), float64(1), float64(2), float64(3)} - if Compare(result, expected) != 0 { + if util.Compare(result, expected) != 0 { t.Errorf("Unexpected result in tracing test: %v", result) return } diff --git a/eval/compare.go b/util/compare.go similarity index 99% rename from eval/compare.go rename to util/compare.go index 640af59a2d..6825f92837 100644 --- a/eval/compare.go +++ b/util/compare.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package util import ( "fmt" diff --git a/eval/compare_test.go b/util/compare_test.go similarity index 99% rename from eval/compare_test.go rename to util/compare_test.go index 6cdef3565e..e32635a03b 100644 --- a/eval/compare_test.go +++ b/util/compare_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package util import "testing" import "math" From 51527395b3a1ce6a2ca68fad2726e1d44085f473 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Fri, 13 May 2016 16:34:45 -0700 Subject: [PATCH 5/9] Move storage code into storage package - Move storage-related code out of eval - Rename old Storage type to DataStore - A few miscellaneous renamings for store pointers --- Makefile | 1 + eval/topdown.go | 124 +++++++-------- eval/topdown_test.go | 65 ++++---- eval/tracer_test.go | 13 +- runtime/repl.go | 7 +- runtime/repl_test.go | 12 +- runtime/runtime.go | 22 +-- runtime/runtime_test.go | 10 +- runtime/server.go | 19 +-- {eval => storage}/bindings.go | 2 +- eval/storage.go => storage/datastore.go | 130 +++++++-------- .../datastore_test.go | 148 ++++++++++++++---- {eval => storage}/index.go | 14 +- {eval => storage}/index_test.go | 6 +- {eval => storage}/policystore.go | 20 +-- {eval => storage}/policystore_test.go | 10 +- 16 files changed, 346 insertions(+), 257 deletions(-) rename {eval => storage}/bindings.go (99%) rename eval/storage.go => storage/datastore.go (81%) rename eval/storage_test.go => storage/datastore_test.go (77%) rename {eval => storage}/index.go (95%) rename {eval => storage}/index_test.go (96%) rename {eval => storage}/policystore.go (93%) rename {eval => storage}/policystore_test.go (98%) diff --git a/Makefile b/Makefile index 06ca9d5d9d..f6c13bd1ae 100644 --- a/Makefile +++ b/Makefile @@ -7,6 +7,7 @@ PACKAGES := \ github.com/open-policy-agent/opa/cmd/.../ \ github.com/open-policy-agent/opa/eval/.../ \ github.com/open-policy-agent/opa/runtime/.../ \ + github.com/open-policy-agent/opa/storage/.../ \ github.com/open-policy-agent/opa/util/.../ BUILD_COMMIT := $(shell ./build/get-build-commit.sh) diff --git a/eval/topdown.go b/eval/topdown.go index f416fa2f86..e30528b880 100644 --- a/eval/topdown.go +++ b/eval/topdown.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/util" "github.com/pkg/errors" ) @@ -19,20 +20,20 @@ import ( // step and binding. This avoids the need to undo steps and bindings // each time the proof fails but this may be too expensive. type TopDownContext struct { - Query ast.Body - Bindings *Bindings - Index int - Previous *TopDownContext - Store *Storage - Tracer Tracer + Query ast.Body + Bindings *storage.Bindings + Index int + Previous *TopDownContext + DataStore *storage.DataStore + Tracer Tracer } // NewTopDownContext creates a new TopDownContext with no bindings. -func NewTopDownContext(query ast.Body, store *Storage) *TopDownContext { +func NewTopDownContext(query ast.Body, ds *storage.DataStore) *TopDownContext { return &TopDownContext{ - Query: query, - Bindings: NewBindings(), - Store: store, + Query: query, + Bindings: storage.NewBindings(), + DataStore: ds, } } @@ -74,8 +75,8 @@ func (ctx *TopDownContext) BindVar(variable ast.Var, value ast.Value) *TopDownCo return nil } cpy := *ctx - cpy.Bindings = NewBindings() - tmp := NewBindings() + cpy.Bindings = storage.NewBindings() + tmp := storage.NewBindings() tmp.Put(variable, value) ctx.Bindings.Iter(func(k, v ast.Value) bool { cpy.Bindings.Put(k, plugValue(v, tmp)) @@ -86,7 +87,7 @@ func (ctx *TopDownContext) BindVar(variable ast.Var, value ast.Value) *TopDownCo } // Child returns a new context to evaluate a rule that was referenced by this context. -func (ctx *TopDownContext) Child(rule *ast.Rule, bindings *Bindings) *TopDownContext { +func (ctx *TopDownContext) Child(rule *ast.Rule, bindings *storage.Bindings) *TopDownContext { cpy := *ctx cpy.Query = rule.Body cpy.Bindings = bindings @@ -144,9 +145,9 @@ func TopDown(ctx *TopDownContext, iter TopDownIterator) error { // TopDownQueryParams defines input parameters for the query interface. type TopDownQueryParams struct { - Store *Storage - Tracer Tracer - Path []string + DataStore *storage.DataStore + Tracer Tracer + Path []string } // TopDownQuery returns the document identified by the path. @@ -160,7 +161,7 @@ func TopDownQuery(params *TopDownQueryParams) (interface{}, error) { ref = append(ref, ast.StringTerm(v)) } - node, err := lookup(params.Store, ref) + node, err := params.DataStore.GetRef(ref) if err != nil { return nil, err } @@ -246,7 +247,7 @@ func ValueToInterface(v ast.Value, ctx *TopDownContext) (interface{}, error) { // References convert to native values via lookup. case ast.Ref: - return lookup(ctx.Store, v) + return ctx.DataStore.GetRef(v) default: // If none of the above cases are hit, something is very wrong, e.g., the caller @@ -423,7 +424,7 @@ func evalEqUnifyArray(ctx *TopDownContext, a ast.Array, b ast.Value, iter TopDow func evalEqUnifyArrayRef(ctx *TopDownContext, a ast.Array, b ast.Ref, iter TopDownIterator) error { - r, err := lookup(ctx.Store, b) + r, err := ctx.DataStore.GetRef(b) if err != nil { return err } @@ -500,7 +501,7 @@ func evalEqUnifyObject(ctx *TopDownContext, a ast.Object, b ast.Value, iter TopD func evalEqUnifyObjectRef(ctx *TopDownContext, a ast.Object, b ast.Ref, iter TopDownIterator) error { - r, err := lookup(ctx.Store, b) + r, err := ctx.DataStore.GetRef(b) if err != nil { return err @@ -659,9 +660,9 @@ func evalRefRec(ctx *TopDownContext, path, tail ast.Ref, iter TopDownIterator) e func evalRefRecEnumColl(ctx *TopDownContext, path, tail ast.Ref, iter TopDownIterator) error { - node, err := lookup(ctx.Store, path) + node, err := ctx.DataStore.GetRef(path) if err != nil { - if IsStorageNotFound(err) { + if storage.IsNotFound(err) { return nil } return err @@ -699,7 +700,7 @@ func evalRefRecEnumColl(ctx *TopDownContext, path, tail ast.Ref, iter TopDownIte } func evalRefRecFinish(ctx *TopDownContext, path ast.Ref, iter TopDownIterator) error { - ok, err := lookupExists(ctx.Store, path) + ok, err := lookupExists(ctx.DataStore, path) if err == nil && ok { return iter(ctx) } @@ -711,9 +712,9 @@ func evalRefRecGround(ctx *TopDownContext, path, tail ast.Ref, iter TopDownItera // If the node exists and is a rule, evaluate the rule to produce a virtual doc. // Otherwise, process the rest of the reference. path = append(path, tail[0]) - node, err := lookupRule(ctx.Store, path) + node, err := lookupRule(ctx.DataStore, path) if err != nil { - if IsStorageNotFound(err) { + if storage.IsNotFound(err) { return nil } return err @@ -762,7 +763,7 @@ func evalRefRuleCompleteDoc(ctx *TopDownContext, ref ast.Ref, path ast.Ref, rule return fmt.Errorf("not implemented: %v %v %v", ref, path, rule) } - bindings := NewBindings() + bindings := storage.NewBindings() child := ctx.Child(rule, bindings) return TopDown(child, func(child *TopDownContext) error { @@ -798,7 +799,7 @@ func evalRefRulePartialObjectDoc(ctx *TopDownContext, ref ast.Ref, path ast.Ref, // NOTE: if at some point multiple variables are supported here, it may be // cleaner to generalize this (instead of having two separate branches). if !key.IsGround() { - child := ctx.Child(rule, NewBindings()) + child := ctx.Child(rule, storage.NewBindings()) return TopDown(child, func(child *TopDownContext) error { key := child.Bindings.Get(rule.Key.Value) if key == nil { @@ -813,7 +814,7 @@ func evalRefRulePartialObjectDoc(ctx *TopDownContext, ref ast.Ref, path ast.Ref, }) } - bindings := NewBindings() + bindings := storage.NewBindings() bindings.Put(rule.Key.Value, key) child := ctx.Child(rule, bindings) @@ -844,7 +845,7 @@ func evalRefRulePartialSetDoc(ctx *TopDownContext, ref ast.Ref, path ast.Ref, ru key := plugValue(suffix[0].Value, ctx.Bindings) if !key.IsGround() { - child := ctx.Child(rule, NewBindings()) + child := ctx.Child(rule, storage.NewBindings()) return TopDown(child, func(child *TopDownContext) error { value := child.Bindings.Get(rule.Key.Value) if value == nil { @@ -861,7 +862,7 @@ func evalRefRulePartialSetDoc(ctx *TopDownContext, ref ast.Ref, path ast.Ref, ru }) } - bindings := NewBindings() + bindings := storage.NewBindings() bindings.Put(rule.Key.Value, key) child := ctx.Child(rule, bindings) @@ -1013,14 +1014,14 @@ func evalTermsIndexed(ctx *TopDownContext, iter TopDownIterator, indexed ast.Ref } // Get the index for the indexed term. If the term is indexed, this should not fail. - index := ctx.Store.Indices.Get(indexed) + index := ctx.DataStore.Indices.Get(indexed) if index == nil { return fmt.Errorf("missing index: %v", indexed) } // Iterate the bindings for the indexed term that when applied to the reference // would locate the non-indexed value obtained above. - return index.Iter(nonIndexedValue, func(bindings *Bindings) error { + return index.Iter(nonIndexedValue, func(bindings *storage.Bindings) error { ctx.Bindings = ctx.Bindings.Update(bindings) return iter(ctx) }) @@ -1166,7 +1167,7 @@ func indexBuildLazy(ctx *TopDownContext, ref ast.Ref) (bool, error) { } // Check if index was already built. - if ctx.Store.Indices.Get(ref) != nil { + if ctx.DataStore.Indices.Get(ref) != nil { return true, nil } @@ -1177,7 +1178,7 @@ func indexBuildLazy(ctx *TopDownContext, ref ast.Ref) (bool, error) { // Ignore refs against virtual docs. tmp := ast.Ref{ref[0], ref[1]} - r, err := lookupRule(ctx.Store, tmp) + r, err := lookupRule(ctx.DataStore, tmp) if err != nil || r != nil { return false, err } @@ -1189,34 +1190,23 @@ func indexBuildLazy(ctx *TopDownContext, ref ast.Ref) (bool, error) { } tmp = append(tmp, p) - r, err := lookupRule(ctx.Store, tmp) + r, err := lookupRule(ctx.DataStore, tmp) if err != nil || r != nil { return false, err } } - if err := ctx.Store.Indices.Build(ctx.Store, ref); err != nil { + if err := ctx.DataStore.Indices.Build(ctx.DataStore, ref); err != nil { return false, err } return true, nil } -func lookup(store *Storage, ref ast.Ref) (interface{}, error) { - if !ref[0].Equal(ast.DefaultRootDocument) { - return nil, fmt.Errorf("illegal root %v: %v", ref[0], ref) - } - path, err := ref[1:].Underlying() - if err != nil { - return nil, err - } - return store.Get(path) -} - -func lookupExists(store *Storage, ref ast.Ref) (bool, error) { - _, err := lookup(store, ref) +func lookupExists(ds *storage.DataStore, ref ast.Ref) (bool, error) { + _, err := ds.GetRef(ref) if err != nil { - if IsStorageNotFound(err) { + if storage.IsNotFound(err) { return false, nil } return false, err @@ -1224,8 +1214,8 @@ func lookupExists(store *Storage, ref ast.Ref) (bool, error) { return true, nil } -func lookupRule(store *Storage, ref ast.Ref) ([]*ast.Rule, error) { - r, err := lookup(store, ref) +func lookupRule(ds *storage.DataStore, ref ast.Ref) ([]*ast.Rule, error) { + r, err := ds.GetRef(ref) if err != nil { return nil, err } @@ -1237,7 +1227,7 @@ func lookupRule(store *Storage, ref ast.Ref) ([]*ast.Rule, error) { } } -func plugExpr(expr *ast.Expr, bindings *Bindings) *ast.Expr { +func plugExpr(expr *ast.Expr, bindings *storage.Bindings) *ast.Expr { plugged := *expr switch ts := plugged.Terms.(type) { case []*ast.Term: @@ -1255,7 +1245,7 @@ func plugExpr(expr *ast.Expr, bindings *Bindings) *ast.Expr { return &plugged } -func plugTerm(term *ast.Term, bindings *Bindings) *ast.Term { +func plugTerm(term *ast.Term, bindings *storage.Bindings) *ast.Term { switch v := term.Value.(type) { case ast.Var: return &ast.Term{Value: plugValue(v, bindings)} @@ -1283,7 +1273,7 @@ func plugTerm(term *ast.Term, bindings *Bindings) *ast.Term { } } -func plugValue(v ast.Value, bindings *Bindings) ast.Value { +func plugValue(v ast.Value, bindings *storage.Bindings) ast.Value { switch v := v.(type) { case ast.Var: @@ -1340,10 +1330,10 @@ func topDownQueryCompleteDoc(params *TopDownQueryParams, rules []*ast.Rule) (int rule := rules[0] ctx := &TopDownContext{ - Query: rule.Body, - Bindings: NewBindings(), - Store: params.Store, - Tracer: params.Tracer, + Query: rule.Body, + Bindings: storage.NewBindings(), + DataStore: params.DataStore, + Tracer: params.Tracer, } isTrue := false @@ -1367,10 +1357,10 @@ func topDownQueryPartialObjectDoc(params *TopDownQueryParams, rules []*ast.Rule) for _, rule := range rules { ctx := &TopDownContext{ - Query: rule.Body, - Bindings: NewBindings(), - Store: params.Store, - Tracer: params.Tracer, + Query: rule.Body, + Bindings: storage.NewBindings(), + DataStore: params.DataStore, + Tracer: params.Tracer, } key := rule.Key.Value.(ast.Var) value := rule.Value.Value.(ast.Var) @@ -1402,10 +1392,10 @@ func topDownQueryPartialSetDoc(params *TopDownQueryParams, rules []*ast.Rule) (i result := []interface{}{} for _, rule := range rules { ctx := &TopDownContext{ - Query: rule.Body, - Bindings: NewBindings(), - Store: params.Store, - Tracer: params.Tracer, + Query: rule.Body, + Bindings: storage.NewBindings(), + DataStore: params.DataStore, + Tracer: params.Tracer, } key := rule.Key.Value.(ast.Var) err := TopDown(ctx, func(ctx *TopDownContext) error { diff --git a/eval/topdown_test.go b/eval/topdown_test.go index 57362d0795..75bc040242 100644 --- a/eval/topdown_test.go +++ b/eval/topdown_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/util" ) @@ -55,8 +56,8 @@ func TestEvalRef(t *testing.T) { data := loadSmallTestData() ctx := &TopDownContext{ - Store: NewStorageFromJSONObject(data), - Bindings: NewBindings(), + DataStore: storage.NewDataStoreFromJSONObject(data), + Bindings: storage.NewBindings(), } for i, tc := range tests { @@ -140,9 +141,9 @@ func TestEvalTerms(t *testing.T) { for i, tc := range tests { ctx := &TopDownContext{ - Query: ast.MustParseBody(tc.body), - Store: NewStorageFromJSONObject(data), - Bindings: NewBindings(), + Query: ast.MustParseBody(tc.body), + DataStore: storage.NewDataStoreFromJSONObject(data), + Bindings: storage.NewBindings(), } expected := loadExpectedBindings(tc.expected) @@ -183,13 +184,13 @@ func TestPlugValue(t *testing.T) { hello := ast.String("hello") world := ast.String("world") - ctx1 := &TopDownContext{Bindings: NewBindings()} + ctx1 := &TopDownContext{Bindings: storage.NewBindings()} ctx1 = ctx1.BindVar(a, b) ctx1 = ctx1.BindVar(b, cs) ctx1 = ctx1.BindVar(c, ks) ctx1 = ctx1.BindVar(k, hello) - ctx2 := &TopDownContext{Bindings: NewBindings()} + ctx2 := &TopDownContext{Bindings: storage.NewBindings()} ctx2 = ctx2.BindVar(a, b) ctx2 = ctx2.BindVar(b, cs) ctx2 = ctx2.BindVar(c, vs) @@ -527,8 +528,8 @@ func TestTopDownEmbeddedVirtualDoc(t *testing.T) { data := loadSmallTestData() - store := NewStorageFromJSONObject(data) - policyStore := NewPolicyStore(store, "") + store := storage.NewDataStoreFromJSONObject(data) + policyStore := storage.NewPolicyStore(store, "") for id, mod := range mods { err := policyStore.Add(id, mod, []byte(""), false) @@ -590,8 +591,8 @@ func TestExample(t *testing.T) { mods := compileModules([]string{vd}) - store := NewStorageFromJSONObject(doc) - policyStore := NewPolicyStore(store, "") + store := storage.NewDataStoreFromJSONObject(doc) + policyStore := storage.NewPolicyStore(store, "") for id, mod := range mods { err := policyStore.Add(id, mod, []byte(""), false) @@ -662,14 +663,14 @@ func compileRules(imports []string, input []string) map[string]*ast.Module { return c.Modules } -func loadExpectedBindings(input string) []*Bindings { +func loadExpectedBindings(input string) []*storage.Bindings { var data []map[string]interface{} if err := json.Unmarshal([]byte(input), &data); err != nil { panic(err) } - var expected []*Bindings + var expected []*storage.Bindings for _, bindings := range data { - buf := NewBindings() + buf := storage.NewBindings() for k, v := range bindings { switch v := v.(type) { case string: @@ -701,7 +702,7 @@ func loadExpectedSortedResult(input string) interface{} { data := loadExpectedResult(input) switch data := data.(type) { case []interface{}: - sort.Sort(ResultSet(data)) + sort.Sort(resultSet(data)) return data default: return data @@ -772,8 +773,8 @@ func runTopDownTestCase(t *testing.T, data map[string]interface{}, i int, note s mods := compileRules(imports, rules) - store := NewStorageFromJSONObject(data) - policyStore := NewPolicyStore(store, "") + store := storage.NewDataStoreFromJSONObject(data) + policyStore := storage.NewPolicyStore(store, "") for id, mod := range mods { err := policyStore.Add(id, mod, []byte(""), false) @@ -785,12 +786,12 @@ func runTopDownTestCase(t *testing.T, data map[string]interface{}, i int, note s assertTopDown(t, store, i, note, []string{"p"}, expected) } -func assertTopDown(t *testing.T, store *Storage, i int, note string, path []string, expected interface{}) { +func assertTopDown(t *testing.T, store *storage.DataStore, i int, note string, path []string, expected interface{}) { switch e := expected.(type) { case error: - result, err := TopDownQuery(&TopDownQueryParams{Store: store, Path: path}) + result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: path}) if err == nil { t.Errorf("Test case %d (%v): expected error but got: %v", i+1, note, result) return @@ -801,7 +802,7 @@ func assertTopDown(t *testing.T, store *Storage, i int, note string, path []stri case string: expected := loadExpectedSortedResult(e) - result, err := TopDownQuery(&TopDownQueryParams{Store: store, Path: path}) + result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: path}) if err != nil { t.Errorf("Test case %d (%v): unexpected error: %v", i+1, note, err) return @@ -812,7 +813,7 @@ func assertTopDown(t *testing.T, store *Storage, i int, note string, path []stri } switch store.MustGet(p).([]*ast.Rule)[0].DocKind() { case ast.PartialSetDoc: - sort.Sort(ResultSet(result.([]interface{}))) + sort.Sort(resultSet(result.([]interface{}))) } if !reflect.DeepEqual(result, expected) { t.Errorf("Test case %d (%v): expected %v but got: %v", i+1, note, expected, result) @@ -820,22 +821,18 @@ func assertTopDown(t *testing.T, store *Storage, i int, note string, path []stri } } -// ResultSet is used to sort set documents produeced by rules for comparison purposes. -type ResultSet []interface{} +type resultSet []interface{} -// Less returns true if the i'th index of resultSet is less than the j'th index. -func (resultSet ResultSet) Less(i, j int) bool { - return util.Compare(resultSet[i], resultSet[j]) < 0 +func (rs resultSet) Less(i, j int) bool { + return util.Compare(rs[i], rs[j]) < 0 } -// Swap exchanges the i'th and j'th values in resultSet. -func (resultSet ResultSet) Swap(i, j int) { - tmp := resultSet[i] - resultSet[i] = resultSet[j] - resultSet[j] = tmp +func (rs resultSet) Swap(i, j int) { + tmp := rs[i] + rs[i] = rs[j] + rs[j] = tmp } -// Len returns the size of the resultSet. -func (resultSet ResultSet) Len() int { - return len(resultSet) +func (rs resultSet) Len() int { + return len(rs) } diff --git a/eval/tracer_test.go b/eval/tracer_test.go index 39e41238f0..f35dbbc09c 100644 --- a/eval/tracer_test.go +++ b/eval/tracer_test.go @@ -8,6 +8,7 @@ import ( "fmt" "testing" + "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/util" ) @@ -30,11 +31,11 @@ func TestTracer(t *testing.T) { "q[i] = j :- a[i] = j", }) - store := NewStorageFromJSONObject(data) - policyStore := NewPolicyStore(store, "") + ds := storage.NewDataStoreFromJSONObject(data) + ps := storage.NewPolicyStore(ds, "") for id, mod := range mods { - err := policyStore.Add(id, mod, []byte(""), false) + err := ps.Add(id, mod, []byte(""), false) if err != nil { panic(err) } @@ -43,9 +44,9 @@ func TestTracer(t *testing.T) { tracer := &mockTracer{[]string{}} params := &TopDownQueryParams{ - Store: store, - Tracer: tracer, - Path: []string{"p"}} + DataStore: ds, + Tracer: tracer, + Path: []string{"p"}} result, err := TopDownQuery(params) if err != nil { diff --git a/runtime/repl.go b/runtime/repl.go index 20a4c457bc..fd4bfbb225 100644 --- a/runtime/repl.go +++ b/runtime/repl.go @@ -15,6 +15,7 @@ import ( "github.com/apcera/termtables" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/storage" "github.com/peterh/liner" ) @@ -113,7 +114,7 @@ func (r *Repl) OneShot(line string) bool { } func (r *Repl) cmdDump() bool { - fmt.Fprintln(r.Output, r.Runtime.Store) + fmt.Fprintln(r.Output, r.Runtime.DataStore) return false } @@ -269,7 +270,7 @@ func (r *Repl) evalStatement(stmt interface{}) bool { func (r *Repl) evalBody(body ast.Body) bool { - ctx := eval.NewTopDownContext(body, r.Runtime.Store) + ctx := eval.NewTopDownContext(body, r.Runtime.DataStore) if r.Trace { ctx.Tracer = &eval.StdoutTracer{} } @@ -406,7 +407,7 @@ func (r *Repl) evalRule(rule *ast.Rule) bool { path := []interface{}{string(rule.Name)} - if err := r.Runtime.Store.Patch(eval.StorageAdd, path, []*ast.Rule{rule}); err != nil { + if err := r.Runtime.DataStore.Patch(storage.AddOp, path, []*ast.Rule{rule}); err != nil { fmt.Fprintln(r.Output, "error:", err) return true } diff --git a/runtime/repl_test.go b/runtime/repl_test.go index c32618cd67..1ac8807772 100644 --- a/runtime/repl_test.go +++ b/runtime/repl_test.go @@ -11,7 +11,7 @@ import ( "testing" "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/storage" ) func TestDump(t *testing.T) { @@ -21,7 +21,7 @@ func TestDump(t *testing.T) { if err != nil { panic(err) } - store := eval.NewStorageFromJSONObject(data) + store := storage.NewDataStoreFromJSONObject(data) var buffer bytes.Buffer repl := newRepl(store, &buffer) repl.cmdDump() @@ -94,13 +94,13 @@ func expectOutput(t *testing.T, output string, expected string) { } } -func newRepl(store *eval.Storage, buffer *bytes.Buffer) *Repl { - runtime := &Runtime{Store: store} +func newRepl(store *storage.DataStore, buffer *bytes.Buffer) *Repl { + runtime := &Runtime{DataStore: store} repl := NewRepl(runtime, "", buffer) return repl } -func newTestStorage() *eval.Storage { +func newTestStorage() *storage.DataStore { input := ` { "a": [ @@ -122,5 +122,5 @@ func newTestStorage() *eval.Storage { if err != nil { panic(err) } - return eval.NewStorageFromJSONObject(data) + return storage.NewDataStoreFromJSONObject(data) } diff --git a/runtime/runtime.go b/runtime/runtime.go index fb66d2f0a5..b976297941 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -12,7 +12,7 @@ import ( "path/filepath" "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/storage" "github.com/pkg/errors" ) @@ -42,8 +42,8 @@ type Params struct { // Runtime represents a single OPA instance. type Runtime struct { - Store *eval.Storage - PolicyStore *eval.PolicyStore + DataStore *storage.DataStore + PolicyStore *storage.PolicyStore } // Init initializes the OPA instance. @@ -61,29 +61,29 @@ func (rt *Runtime) Init(params *Params) error { } // Open data store and load base documents. - dataStore := eval.NewStorage() + ds := storage.NewDataStore() for _, doc := range parsed.docs { for k, v := range doc { - if err := dataStore.Patch(eval.StorageAdd, []interface{}{k}, v); err != nil { + if err := ds.Patch(storage.AddOp, []interface{}{k}, v); err != nil { return errors.Wrap(err, "unable to open data store") } } } // Open policy store and load existing policies. - policyStore := eval.NewPolicyStore(dataStore, params.PolicyDir) - if err := policyStore.Open(eval.LoadPolicies); err != nil { + ps := storage.NewPolicyStore(ds, params.PolicyDir) + if err := ps.Open(storage.LoadPolicies); err != nil { return errors.Wrap(err, "unable to open policy store") } // Load policies provided via input. - if err := compileAndStoreInputs(parsed.modules, policyStore); err != nil { + if err := compileAndStoreInputs(parsed.modules, ps); err != nil { return errors.Wrapf(err, "compile error") } - rt.PolicyStore = policyStore - rt.Store = dataStore + rt.PolicyStore = ps + rt.DataStore = ds return nil } @@ -114,7 +114,7 @@ func (rt *Runtime) startRepl(params *Params) { repl.Loop() } -func compileAndStoreInputs(parsed map[string]*parsedModule, policyStore *eval.PolicyStore) error { +func compileAndStoreInputs(parsed map[string]*parsedModule, policyStore *storage.PolicyStore) error { mods := policyStore.List() for _, p := range parsed { diff --git a/runtime/runtime_test.go b/runtime/runtime_test.go index 2fed36a4a4..26fc55d4c5 100644 --- a/runtime/runtime_test.go +++ b/runtime/runtime_test.go @@ -12,7 +12,7 @@ import ( "testing" "github.com/open-policy-agent/opa/ast" - "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/util" ) func TestInit(t *testing.T) { @@ -76,13 +76,13 @@ func TestInit(t *testing.T) { return } - node, err := rt.Store.Get(path("foo")) - if eval.Compare(node, "bar") != 0 || err != nil { + node, err := rt.DataStore.Get(path("foo")) + if util.Compare(node, "bar") != 0 || err != nil { t.Errorf("Expected %v but got %v (err: %v)", "bar", node, err) return } - node, err = rt.Store.Get(path("a.b.c.p")) + node, err = rt.DataStore.Get(path("a.b.c.p")) rules, ok := node.([]*ast.Rule) if !ok { t.Errorf("Expected rules but got: %v", node) @@ -93,7 +93,7 @@ func TestInit(t *testing.T) { return } - node, err = rt.Store.Get(path("a.b.c.q")) + node, err = rt.DataStore.Get(path("a.b.c.q")) rules, ok = node.([]*ast.Rule) if !ok { t.Errorf("Expected rules but got: %v", node) diff --git a/runtime/server.go b/runtime/server.go index 1b36686d40..f7fffd465a 100644 --- a/runtime/server.go +++ b/runtime/server.go @@ -17,6 +17,7 @@ import ( "github.com/gorilla/mux" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/eval" + "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/version" "github.com/pkg/errors" ) @@ -129,7 +130,7 @@ func (s *Server) execQuery(qStr string) (resultSetV1, error) { compiled := c.Modules[""].Rules[0].Body - ctx := eval.NewTopDownContext(compiled, s.Runtime.Store) + ctx := eval.NewTopDownContext(compiled, s.Runtime.DataStore) results := resultSetV1{} @@ -194,8 +195,8 @@ func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) path := strings.Split(vars["path"], "/") params := &eval.TopDownQueryParams{ - Store: s.Runtime.Store, - Path: path, + DataStore: s.Runtime.DataStore, + Path: path, } s.mtx.RLock() @@ -231,16 +232,16 @@ func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) { for i := range ops { - var op eval.StorageOp + var op storage.PatchOp // TODO this could be refactored for failure handling switch ops[i].Op { case "add": - op = eval.StorageAdd + op = storage.AddOp case "remove": - op = eval.StorageRemove + op = storage.RemoveOp case "replace": - op = eval.StorageReplace + op = storage.ReplaceOp default: handleErrorf(w, 400, "bad patch operation: %v", ops[i].Op) return @@ -255,7 +256,7 @@ func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) { path = append(path, x) } - if err := s.Runtime.Store.Patch(op, path, ops[i].Value); err != nil { + if err := s.Runtime.DataStore.Patch(op, path, ops[i].Value); err != nil { handleErrorAuto(w, err) return } @@ -427,7 +428,7 @@ func handleError(w http.ResponseWriter, code int, err error) { func handleErrorAuto(w http.ResponseWriter, err error) { var prev error for curr := err; curr != prev; { - if eval.IsStorageNotFound(curr) { + if storage.IsNotFound(curr) { handleError(w, 404, err) return } diff --git a/eval/bindings.go b/storage/bindings.go similarity index 99% rename from eval/bindings.go rename to storage/bindings.go index f62a916789..d506f3e1f9 100644 --- a/eval/bindings.go +++ b/storage/bindings.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "github.com/open-policy-agent/opa/ast" diff --git a/eval/storage.go b/storage/datastore.go similarity index 81% rename from eval/storage.go rename to storage/datastore.go index a75ba58c7e..bea20a3471 100644 --- a/eval/storage.go +++ b/storage/datastore.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "fmt" @@ -10,34 +10,34 @@ import ( "github.com/open-policy-agent/opa/ast" ) -// StorageErrorCode represents the collection of error types that can be +// ErrCode represents the collection of error types that can be // returned by Storage. -type StorageErrorCode int +type ErrCode int const ( - // StorageInternalErr indicates an unknown, internal error has occurred. - StorageInternalErr StorageErrorCode = iota + // InternalErr indicates an unknown, internal error has occurred. + InternalErr ErrCode = iota - // StorageNotFoundErr indicates the path used in the storage operation does not + // NotFoundErr indicates the path used in the storage operation does not // locate a document. - StorageNotFoundErr = iota + NotFoundErr = iota ) -// StorageError is the error type returned by Storage functions. -type StorageError struct { - Code StorageErrorCode +// Error is the error type returned by Storage functions. +type Error struct { + Code ErrCode Message string } -func (err *StorageError) Error() string { +func (err *Error) Error() string { return fmt.Sprintf("storage error (code: %d): %v", err.Code, err.Message) } -// IsStorageNotFound returns true if this error is a StorageNotFoundErr -func IsStorageNotFound(err error) bool { +// IsNotFound returns true if this error is a NotFoundErr +func IsNotFound(err error) bool { switch err := err.(type) { - case *StorageError: - return err.Code == StorageNotFoundErr + case *Error: + return err.Code == NotFoundErr } return false } @@ -63,7 +63,7 @@ func nonArrayMsg(v interface{}) string { return fmt.Sprintf("path refers to non-array document with element %v", v) } -func notFoundError(path []interface{}, f string, a ...interface{}) *StorageError { +func notFoundError(path []interface{}, f string, a ...interface{}) *Error { msg := fmt.Sprintf("bad path: %v", path) if len(f) > 0 { msg += ", " + fmt.Sprintf(f, a...) @@ -71,58 +71,71 @@ func notFoundError(path []interface{}, f string, a ...interface{}) *StorageError return notFoundErrorf(msg) } -func notFoundErrorf(f string, a ...interface{}) *StorageError { +func notFoundErrorf(f string, a ...interface{}) *Error { msg := fmt.Sprintf(f, a...) - return &StorageError{ - Code: StorageNotFoundErr, + return &Error{ + Code: NotFoundErr, Message: msg, } } -// Storage is the backend containing rules and data. -type Storage struct { +// DataStore is the backend containing rule references and data. +type DataStore struct { Indices *Indices data map[string]interface{} } -// NewStorage is a helper for creating a new, empty Storage. -func NewStorage() *Storage { - return &Storage{ +// NewDataStore returns an empty DataStore. +func NewDataStore() *DataStore { + return &DataStore{ Indices: NewIndices(), data: map[string]interface{}{}, } } -// NewStorageFromJSONObject returns Storage by converting from map[string]interface{} -// This is mostly for test purposes. -func NewStorageFromJSONObject(data map[string]interface{}) *Storage { - store := NewStorage() +// NewDataStoreFromJSONObject returns a new DataStore containing +// the supplied documents. This is mostly for test purposes. +func NewDataStoreFromJSONObject(data map[string]interface{}) *DataStore { + ds := NewDataStore() for k, v := range data { - if err := store.Patch(StorageAdd, []interface{}{k}, v); err != nil { + if err := ds.Patch(AddOp, []interface{}{k}, v); err != nil { panic(err) } } - return store + return ds } // Get returns the value in Storage referenced by path. // If the lookup fails, an error is returned with a message indicating // why the failure occurred. -func (store *Storage) Get(path []interface{}) (interface{}, error) { - return get(store.data, path) +func (ds *DataStore) Get(path []interface{}) (interface{}, error) { + return get(ds.data, path) +} + +// GetRef returns the value in Storage referred to by the reference. +// This is a convienence function. +func (ds *DataStore) GetRef(ref ast.Ref) (interface{}, error) { + if !ref[0].Equal(ast.DefaultRootDocument) { + return nil, fmt.Errorf("illegal root %v: %v", ref[0], ref) + } + path, err := ref[1:].Underlying() + if err != nil { + return nil, err + } + return ds.Get(path) } // MakePath ensures the specified path exists by creating elements as necessary. -func (store *Storage) MakePath(path []interface{}) error { +func (ds *DataStore) MakePath(path []interface{}) error { var tmp []interface{} for _, p := range path { tmp = append(tmp, p) - node, err := store.Get(tmp) + node, err := ds.Get(tmp) if err != nil { switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { - err := store.Patch(StorageAdd, tmp, map[string]interface{}{}) + case *Error: + if err.Code == NotFoundErr { + err := ds.Patch(AddOp, tmp, map[string]interface{}{}) if err != nil { return err } @@ -143,27 +156,22 @@ func (store *Storage) MakePath(path []interface{}) error { // MustGet returns the value in Storage reference by path. // If the lookup fails, the function will panic. -func (store *Storage) MustGet(path []interface{}) interface{} { - return mustGet(store.data, path) +func (ds *DataStore) MustGet(path []interface{}) interface{} { + return mustGet(ds.data, path) } -// StorageOp is the enumeration of supposed modifications. -type StorageOp int +// PatchOp is the enumeration of supposed modifications. +type PatchOp int +// Patch supports add, remove, and replace operations. const ( - - // StorageAdd represents an additive operation. - StorageAdd StorageOp = iota - - // StorageRemove represents a removal operation. - StorageRemove = iota - - // StorageReplace represents a replacement operation. - StorageReplace = iota + AddOp PatchOp = iota + RemoveOp = iota + ReplaceOp = iota ) // Patch modifies the store by performing the associated add/remove/replace operation on the given path. -func (store *Storage) Patch(op StorageOp, path []interface{}, value interface{}) error { +func (ds *DataStore) Patch(op PatchOp, path []interface{}, value interface{}) error { if len(path) == 0 { return notFoundError(path, nonEmptyMsg) @@ -179,7 +187,7 @@ func (store *Storage) Patch(op StorageOp, path []interface{}, value interface{}) // the use cases, we can optimize this. r := []ast.Ref{} - err := store.Indices.Iter(func(ref ast.Ref, index *Index) error { + err := ds.Indices.Iter(func(ref ast.Ref, index *Index) error { if !commonPrefix(ref[1:], path) { return nil } @@ -192,25 +200,25 @@ func (store *Storage) Patch(op StorageOp, path []interface{}, value interface{}) } for _, ref := range r { - store.Indices.Drop(ref) + ds.Indices.Drop(ref) } // Perform in-place update on data. switch op { - case StorageAdd: - return add(store.data, path, value) - case StorageRemove: - return remove(store.data, path) - case StorageReplace: - return replace(store.data, path, value) + case AddOp: + return add(ds.data, path, value) + case RemoveOp: + return remove(ds.data, path) + case ReplaceOp: + return replace(ds.data, path, value) } // Unreachable. return nil } -func (store *Storage) String() string { - return fmt.Sprintf("%v", store.data) +func (ds *DataStore) String() string { + return fmt.Sprintf("%v", ds.data) } // commonPrefix returns true the reference is a prefix of the path or vice versa. diff --git a/eval/storage_test.go b/storage/datastore_test.go similarity index 77% rename from eval/storage_test.go rename to storage/datastore_test.go index 1d9b6e5af1..95a21ce230 100644 --- a/eval/storage_test.go +++ b/storage/datastore_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "encoding/json" @@ -39,7 +39,7 @@ func TestStorageGet(t *testing.T) { {"b.vdeadbeef", notFoundError(path("b.vdeadbeef"), doesNotExistMsg)}, } - store := NewStorageFromJSONObject(data) + ds := NewDataStoreFromJSONObject(data) for idx, tc := range tests { ref := ast.MustParseRef(tc.ref) @@ -47,7 +47,7 @@ func TestStorageGet(t *testing.T) { if err != nil { panic(err) } - result, err := store.Get(path) + result, err := ds.Get(path) switch e := tc.expected.(type) { case error: if err == nil { @@ -121,24 +121,24 @@ func TestStoragePatch(t *testing.T) { for i, tc := range tests { data := loadSmallTestData() - store := NewStorageFromJSONObject(data) + ds := NewDataStoreFromJSONObject(data) // Perform patch and check result value := loadExpectedSortedResult(tc.value) - var op StorageOp + var op PatchOp switch tc.op { case "add": - op = StorageAdd + op = AddOp case "remove": - op = StorageRemove + op = RemoveOp case "replace": - op = StorageReplace + op = ReplaceOp default: panic(fmt.Sprintf("illegal value: %v", tc.op)) } - err := store.Patch(op, path(tc.path), value) + err := ds.Patch(op, path(tc.path), value) if tc.expected == nil { if err != nil { @@ -161,7 +161,7 @@ func TestStoragePatch(t *testing.T) { } // Perform get and verify result - result, err := store.Get(path(tc.getPath)) + result, err := ds.Get(path(tc.getPath)) switch expected := tc.getExpected.(type) { case error: if err == nil { @@ -192,16 +192,16 @@ func TestStoragePatch(t *testing.T) { func TestStorageIndexingBasicUpdate(t *testing.T) { refA := ast.MustParseRef("data.a[i]") refB := ast.MustParseRef("data.b[x]") - store := newStorageWithIndices(refA, refB) + ds := newStorageWithIndices(refA, refB) - mustPatch(store, StorageAdd, path(`a["-"]`), float64(100)) + mustPatch(ds, AddOp, path(`a["-"]`), float64(100)) - index := store.Indices.Get(refA) + index := ds.Indices.Get(refA) if index != nil { t.Errorf("Expected index to be removed after patch: %v", index) } - index = store.Indices.Get(refB) + index = ds.Indices.Get(refB) if index == nil { t.Errorf("Expected index to be intact after patch: %v", refB) } @@ -210,16 +210,16 @@ func TestStorageIndexingBasicUpdate(t *testing.T) { func TestStorageIndexingAddDeepPath(t *testing.T) { ref := ast.MustParseRef("data.l[x]") refD := ast.MustParseRef("data.l[x].d") - store := newStorageWithIndices(ref, refD) + ds := newStorageWithIndices(ref, refD) - mustPatch(store, StorageAdd, path(`l[0].c["-"]`), float64(5)) + mustPatch(ds, AddOp, path(`l[0].c["-"]`), float64(5)) - index := store.Indices.Get(ref) + index := ds.Indices.Get(ref) if index != nil { t.Errorf("Expected index to be removed after patch: %v", index) } - index = store.Indices.Get(refD) + index = ds.Indices.Get(refD) if index == nil { t.Errorf("Expected index to be intact after patch: %v", refD) } @@ -227,41 +227,131 @@ func TestStorageIndexingAddDeepPath(t *testing.T) { func TestStorageIndexingAddDeepRef(t *testing.T) { ref := ast.MustParseRef("data.l[x].a") - store := newStorageWithIndices(ref) + ds := newStorageWithIndices(ref) var data interface{} json.Unmarshal([]byte(`{"a": "eve", "b": 100, "c": [999,999,999]}`), &data) - mustPatch(store, StorageAdd, path(`l["-"]`), data) + mustPatch(ds, AddOp, path(`l["-"]`), data) - index := store.Indices.Get(ref) + index := ds.Indices.Get(ref) if index != nil { t.Errorf("Expected index to be removed after patch: %v", index) } } -func newStorageWithIndices(r ...ast.Ref) *Storage { - data := loadSmallTestData() - store := NewStorageFromJSONObject(data) - for _, x := range r { - mustBuild(store, x) +func loadExpectedBindings(input string) []*Bindings { + var data []map[string]interface{} + if err := json.Unmarshal([]byte(input), &data); err != nil { + panic(err) } - return store + var expected []*Bindings + for _, bindings := range data { + buf := NewBindings() + for k, v := range bindings { + switch v := v.(type) { + case string: + buf.Put(ast.Var(k), ast.String(v)) + case float64: + buf.Put(ast.Var(k), ast.Number(v)) + default: + panic("unreachable") + } + } + expected = append(expected, buf) + } + + return expected +} + +func loadExpectedResult(input string) interface{} { + if len(input) == 0 { + return nil + } + var data interface{} + if err := json.Unmarshal([]byte(input), &data); err != nil { + panic(err) + } + return data +} + +func loadExpectedSortedResult(input string) interface{} { + data := loadExpectedResult(input) + switch data := data.(type) { + case []interface{}: + return data + default: + return data + } +} + +func loadSmallTestData() map[string]interface{} { + var data map[string]interface{} + err := json.Unmarshal([]byte(`{ + "a": [1,2,3,4], + "b": { + "v1": "hello", + "v2": "goodbye" + }, + "c": [{ + "x": [true, false, "foo"], + "y": [null, 3.14159], + "z": {"p": true, "q": false} + }], + "d": { + "e": ["bar", "baz"] + }, + "g": { + "a": [1, 0, 0, 0], + "b": [0, 2, 0, 0], + "c": [0, 0, 0, 4] + }, + "h": [ + [1,2,3], + [2,3,4] + ], + "l": [ + { + "a": "bob", + "b": -1, + "c": [1,2,3,4] + }, + { + "a": "alice", + "b": 1, + "c": [2,3,4,5], + "d": null + } + ] + }`), &data) + if err != nil { + panic(err) + } + return data } -func mustBuild(store *Storage, ref ast.Ref) { +func mustBuild(store *DataStore, ref ast.Ref) { err := store.Indices.Build(store, ref) if err != nil { panic(err) } } -func mustPatch(store *Storage, op StorageOp, path []interface{}, value interface{}) { +func mustPatch(store *DataStore, op PatchOp, path []interface{}, value interface{}) { err := store.Patch(op, path, value) if err != nil { panic(err) } } +func newStorageWithIndices(r ...ast.Ref) *DataStore { + data := loadSmallTestData() + store := NewDataStoreFromJSONObject(data) + for _, x := range r { + mustBuild(store, x) + } + return store +} + func path(input interface{}) []interface{} { switch input := input.(type) { case []interface{}: diff --git a/eval/index.go b/storage/index.go similarity index 95% rename from eval/index.go rename to storage/index.go index 07facc608d..7c3e4a1602 100644 --- a/eval/index.go +++ b/storage/index.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "fmt" @@ -50,7 +50,7 @@ func NewIndices() *Indices { // Build initializes the references' index by walking the store for the reference and // creating the index that maps values to bindings. -func (ind *Indices) Build(store *Storage, ref ast.Ref) error { +func (ind *Indices) Build(store *DataStore, ref ast.Ref) error { index := NewIndex() err := iterStorage(store, ref, ast.EmptyRef(), NewBindings(), func(bindings *Bindings, val interface{}) { index.Add(val, bindings) @@ -289,12 +289,12 @@ func hash(v interface{}) int { panic(fmt.Sprintf("illegal argument: %v (%T)", v, v)) } -func iterStorage(store *Storage, ref ast.Ref, path ast.Ref, bindings *Bindings, iter func(*Bindings, interface{})) error { +func iterStorage(store *DataStore, ref ast.Ref, path ast.Ref, bindings *Bindings, iter func(*Bindings, interface{})) error { if len(ref) == 0 { - node, err := lookup(store, path) + node, err := store.GetRef(path) if err != nil { - if IsStorageNotFound(err) { + if IsNotFound(err) { return nil } return err @@ -314,9 +314,9 @@ func iterStorage(store *Storage, ref ast.Ref, path ast.Ref, bindings *Bindings, return iterStorage(store, tail, path, bindings, iter) } - node, err := lookup(store, path) + node, err := store.GetRef(path) if err != nil { - if IsStorageNotFound(err) { + if IsNotFound(err) { return nil } return err diff --git a/eval/index_test.go b/storage/index_test.go similarity index 96% rename from eval/index_test.go rename to storage/index_test.go index ea41d94a1b..6157170f90 100644 --- a/eval/index_test.go +++ b/storage/index_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "encoding/json" @@ -46,7 +46,7 @@ func TestIndicesAdd(t *testing.T) { indices := NewIndices() data := loadSmallTestData() - store := NewStorageFromJSONObject(data) + store := NewDataStoreFromJSONObject(data) ref := ast.MustParseRef("data.d[x][y]") @@ -76,7 +76,7 @@ func runIndexBuildTestCase(t *testing.T, i int, note string, refStr string, expe indices := NewIndices() data := loadSmallTestData() - store := NewStorageFromJSONObject(data) + store := NewDataStoreFromJSONObject(data) ref := ast.MustParseRef(refStr) if indices.Get(ref) != nil { diff --git a/eval/policystore.go b/storage/policystore.go similarity index 93% rename from eval/policystore.go rename to storage/policystore.go index bebcfd8a16..e4e6eb7d99 100644 --- a/eval/policystore.go +++ b/storage/policystore.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "fmt" @@ -18,7 +18,7 @@ import ( // PolicyStore provides a storage abstraction for policy definitions and modules. // type PolicyStore struct { - dataStore *Storage + dataStore *DataStore policyDir string raw map[string][]byte modules map[string]*ast.Module @@ -47,7 +47,7 @@ func LoadPolicies(bufs map[string][]byte) (map[string]*ast.Module, error) { } // NewPolicyStore returns an empty PolicyStore. -func NewPolicyStore(store *Storage, policyDir string) *PolicyStore { +func NewPolicyStore(store *DataStore, policyDir string) *PolicyStore { return &PolicyStore{ dataStore: store, policyDir: policyDir, @@ -232,10 +232,10 @@ func (p *PolicyStore) installRule(path []interface{}, rule *ast.Rule) error { node, err := p.dataStore.Get(path) if err != nil { switch err := err.(type) { - case *StorageError: - if err.Code == StorageNotFoundErr { + case *Error: + if err.Code == NotFoundErr { rules := []*ast.Rule{rule} - if err := p.dataStore.Patch(StorageAdd, path, rules); err != nil { + if err := p.dataStore.Patch(AddOp, path, rules); err != nil { return errors.Wrapf(err, "unable to add new rule set") } return nil @@ -257,7 +257,7 @@ func (p *PolicyStore) installRule(path []interface{}, rule *ast.Rule) error { rs = append(rs, rule) - if err := p.dataStore.Patch(StorageReplace, path, rs); err != nil { + if err := p.dataStore.Patch(ReplaceOp, path, rs); err != nil { return errors.Wrapf(err, "unable to add rule to existing rule set") } @@ -290,7 +290,7 @@ func (p *PolicyStore) uninstallRule(path []interface{}, rule *ast.Rule) error { node, err := p.dataStore.Get(path) - if IsStorageNotFound(err) { + if IsNotFound(err) { return nil } @@ -314,8 +314,8 @@ func (p *PolicyStore) uninstallRule(path []interface{}, rule *ast.Rule) error { } if len(rs) == 0 { - return p.dataStore.Patch(StorageRemove, path, nil) + return p.dataStore.Patch(RemoveOp, path, nil) } - return p.dataStore.Patch(StorageReplace, path, rs) + return p.dataStore.Patch(ReplaceOp, path, rs) } diff --git a/eval/policystore_test.go b/storage/policystore_test.go similarity index 98% rename from eval/policystore_test.go rename to storage/policystore_test.go index b627dadf1d..3b5556d25f 100644 --- a/eval/policystore_test.go +++ b/storage/policystore_test.go @@ -2,7 +2,7 @@ // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. -package eval +package storage import ( "io/ioutil" @@ -29,7 +29,7 @@ func TestPolicyStoreDefaultOpen(t *testing.T) { panic(err) } - dataStore := NewStorage() + dataStore := NewDataStore() policyStore := NewPolicyStore(dataStore, dir) err = policyStore.Open(LoadPolicies) @@ -236,7 +236,7 @@ func TestPolicyStoreUpdate(t *testing.T) { } node, err = f.dataStore.Get(path("a.b.q")) - if !IsStorageNotFound(err) { + if !IsNotFound(err) { t.Errorf("Expected storage not found error but got: %v (err: %v)", node, err) return } @@ -259,7 +259,7 @@ const ( type fixture struct { policyStore *PolicyStore - dataStore *Storage + dataStore *DataStore } func newFixture() *fixture { @@ -269,7 +269,7 @@ func newFixture() *fixture { panic(err) } - dataStore := NewStorage() + dataStore := NewDataStore() policyStore := NewPolicyStore(dataStore, dir) err = policyStore.Open(func(map[string][]byte) (map[string]*ast.Module, error) { return nil, nil From 1b982bc285a7cba0ea5171afa7a75971309d2b54 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Fri, 13 May 2016 17:41:27 -0700 Subject: [PATCH 6/9] Fix array access in Data API Assume that numbers in the Data API paths refer to indices. --- eval/topdown.go | 15 +++++++++-- eval/topdown_test.go | 9 +++++-- eval/tracer_test.go | 2 +- runtime/server.go | 23 ++++++++++++++--- runtime/server_test.go | 58 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 98 insertions(+), 9 deletions(-) diff --git a/eval/topdown.go b/eval/topdown.go index e30528b880..3aeb079695 100644 --- a/eval/topdown.go +++ b/eval/topdown.go @@ -147,7 +147,7 @@ func TopDown(ctx *TopDownContext, iter TopDownIterator) error { type TopDownQueryParams struct { DataStore *storage.DataStore Tracer Tracer - Path []string + Path []interface{} } // TopDownQuery returns the document identified by the path. @@ -158,7 +158,18 @@ func TopDownQuery(params *TopDownQueryParams) (interface{}, error) { ref := ast.Ref{ast.DefaultRootDocument} for _, v := range params.Path { - ref = append(ref, ast.StringTerm(v)) + switch v := v.(type) { + case float64: + ref = append(ref, ast.NumberTerm(v)) + case string: + ref = append(ref, ast.StringTerm(v)) + case bool: + ref = append(ref, ast.BooleanTerm(v)) + case nil: + ref = append(ref, ast.NullTerm()) + default: + return nil, fmt.Errorf("bad path element: %v (%T)", v, v) + } } node, err := params.DataStore.GetRef(ref) diff --git a/eval/topdown_test.go b/eval/topdown_test.go index 75bc040242..2f648771c7 100644 --- a/eval/topdown_test.go +++ b/eval/topdown_test.go @@ -788,10 +788,15 @@ func runTopDownTestCase(t *testing.T, data map[string]interface{}, i int, note s func assertTopDown(t *testing.T, store *storage.DataStore, i int, note string, path []string, expected interface{}) { + p := []interface{}{} + for _, x := range path { + p = append(p, x) + } + switch e := expected.(type) { case error: - result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: path}) + result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: p}) if err == nil { t.Errorf("Test case %d (%v): expected error but got: %v", i+1, note, result) return @@ -802,7 +807,7 @@ func assertTopDown(t *testing.T, store *storage.DataStore, i int, note string, p case string: expected := loadExpectedSortedResult(e) - result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: path}) + result, err := TopDownQuery(&TopDownQueryParams{DataStore: store, Path: p}) if err != nil { t.Errorf("Test case %d (%v): unexpected error: %v", i+1, note, err) return diff --git a/eval/tracer_test.go b/eval/tracer_test.go index f35dbbc09c..8ff6ab5931 100644 --- a/eval/tracer_test.go +++ b/eval/tracer_test.go @@ -46,7 +46,7 @@ func TestTracer(t *testing.T) { params := &TopDownQueryParams{ DataStore: ds, Tracer: tracer, - Path: []string{"p"}} + Path: []interface{}{"p"}} result, err := TopDownQuery(params) if err != nil { diff --git a/runtime/server.go b/runtime/server.go index f7fffd465a..0be393b4c9 100644 --- a/runtime/server.go +++ b/runtime/server.go @@ -10,6 +10,7 @@ import ( "io" "io/ioutil" "net/http" + "strconv" "strings" "sync" "time" @@ -193,7 +194,8 @@ func (s *Server) registerHandlerV1(path string, method string, h func(http.Respo func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - path := strings.Split(vars["path"], "/") + path := splitPath(vars["path"]) + params := &eval.TopDownQueryParams{ DataStore: s.Runtime.DataStore, Path: path, @@ -214,7 +216,7 @@ func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - root := strings.Split(vars["path"], "/") + root := splitPath(vars["path"]) ops := []patchV1{} if err := json.NewDecoder(r.Body).Decode(&ops); err != nil { @@ -247,8 +249,7 @@ func (s *Server) v1DataPatch(w http.ResponseWriter, r *http.Request) { return } - parts := strings.Split(ops[i].Path[1:], "/") - + parts := splitPath(ops[i].Path[1:]) for _, x := range parts { if x == "" { continue @@ -421,6 +422,20 @@ func (s *Server) v1QueryGet(w http.ResponseWriter, r *http.Request) { handleResponseJSON(w, 200, results) } +func splitPath(s string) []interface{} { + p := strings.Split(s, "/") + r := []interface{}{} + for _, x := range p { + i, err := strconv.Atoi(x) + if err != nil { + r = append(r, x) + } else { + r = append(r, float64(i)) + } + } + return r +} + func handleError(w http.ResponseWriter, code int, err error) { handleErrorf(w, code, err.Error()) } diff --git a/runtime/server_test.go b/runtime/server_test.go index 53710011f7..8ceb6acf72 100644 --- a/runtime/server_test.go +++ b/runtime/server_test.go @@ -59,6 +59,64 @@ func TestDataPatchV1(t *testing.T) { } } +func TestDataPatchArrayAccessV1(t *testing.T) { + f := newFixture(t) + patch1 := newReqV1("PATCH", "/data/x", `[{"op": "add", "path": "/", "value": { + "y": [ + {"z": [ + 1, 2, 3 + ]}, + {"z": [ + 4, 5, 6 + ]} + ] + }}]`) + + f.server.Router.ServeHTTP(f.recorder, patch1) + + if f.recorder.Code != 204 { + t.Errorf("Unexpected error: %v", f.recorder) + return + } + + get1 := newReqV1("GET", "/data/x/y/1/z/2", "") + f.reset() + f.server.Router.ServeHTTP(f.recorder, get1) + + resp := f.loadResponse().(float64) + exp1 := float64(6) + if exp1 != resp { + t.Errorf("Expected %v but got: %v", exp1, resp) + return + } + + patch2 := newReqV1("PATCH", "/data/x/y/1", `[{"op": "add", "path": "/z/1", "value": 100}]`) + f.reset() + f.server.Router.ServeHTTP(f.recorder, patch2) + + if f.recorder.Code != 204 { + t.Errorf("Unexpected error: %v", f.recorder) + return + } + + get2 := newReqV1("GET", "/data/x/y/1/z", "") + f.reset() + f.server.Router.ServeHTTP(f.recorder, get2) + + if f.recorder.Code != 200 { + t.Errorf("Unexpected error: %v", f.recorder) + return + } + + resp2 := f.loadResponse().([]interface{}) + exp2 := []interface{}{float64(4), float64(100), float64(5), float64(6)} + if !reflect.DeepEqual(exp2, resp2) { + t.Errorf("Expected %v but got: %v", exp2, resp2) + return + } + +} + func TestIndexGet(t *testing.T) { f := newFixture(t) get, err := http.NewRequest("GET", `/?q=foo = 1`, strings.NewReader("")) From be7aa197768bb943e5789593c47f845fcbea4491 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Sat, 14 May 2016 09:39:16 -0700 Subject: [PATCH 7/9] Add github.com/golang/glog dependency --- glide.lock | 10 +- glide.yaml | 1 + vendor/github.com/golang/glog/LICENSE | 191 +++ vendor/github.com/golang/glog/README | 44 + vendor/github.com/golang/glog/glog.go | 1180 +++++++++++++++++ vendor/github.com/golang/glog/glog_file.go | 124 ++ vendor/github.com/golang/glog/glog_test.go | 415 ++++++ vendor/github.com/pkg/errors/README.md | 2 +- vendor/github.com/pkg/errors/errors.go | 11 +- .../x/tools/go/gcimporter15/bexport.go | 33 +- .../x/tools/go/gcimporter15/bimport.go | 56 +- vendor/golang.org/x/tools/imports/fix.go | 18 +- vendor/golang.org/x/tools/imports/fix_test.go | 54 + 13 files changed, 2100 insertions(+), 39 deletions(-) create mode 100644 vendor/github.com/golang/glog/LICENSE create mode 100644 vendor/github.com/golang/glog/README create mode 100644 vendor/github.com/golang/glog/glog.go create mode 100644 vendor/github.com/golang/glog/glog_file.go create mode 100644 vendor/github.com/golang/glog/glog_test.go diff --git a/glide.lock b/glide.lock index a06d7e6594..b81c22b59d 100644 --- a/glide.lock +++ b/glide.lock @@ -1,11 +1,13 @@ -hash: 31c9b7e9f98ce4ccaadc502360c930f22151e9ccb77eba12f030fd87edfd8c9f -updated: 2016-05-09T16:58:07.015114036-07:00 +hash: 3a5ccacd36f8f645111341d62e7d4dec495008b9a8aafdbaedf3de4c8547bd07 +updated: 2016-05-14T09:38:59.09198485-07:00 imports: - name: github.com/apcera/termtables version: 683d3fb424194f29991b0442b37521de9bc9d66b subpackages: - locale - term +- name: github.com/golang/glog + version: 23def4e6c14b4da8ac2ed8007337bc5eb5007998 - name: github.com/golang/lint version: c7bacac2b21ca01afa1dee0acf64df3ce047c28f - name: github.com/gorilla/context @@ -17,7 +19,7 @@ imports: - name: github.com/peterh/liner version: 0e4af131b90a9786839c8b1b01717be263e8555a - name: github.com/pkg/errors - version: 502e17a0cb34bd200593552492e458d89cf6a64f + version: d814416a46cbb066b728cfff58d30a986bc9ddbe - name: github.com/PuerkitoBio/pigeon version: a5221784523de14130c00a8c389148a1b2ad260c - name: github.com/spf13/cobra @@ -25,7 +27,7 @@ imports: - name: github.com/spf13/pflag version: cb88ea77998c3f024757528e3305022ab50b43be - name: golang.org/x/tools - version: 3f1f7eeff104d9ef829677f12b9780dfdd26a96a + version: c86fe5956d4575f29850535871a97abbd403a145 subpackages: - cmd/goimports devImports: [] diff --git a/glide.yaml b/glide.yaml index 232ebfdc9f..22d5fba9bb 100644 --- a/glide.yaml +++ b/glide.yaml @@ -11,3 +11,4 @@ import: - package: github.com/pkg/errors - package: github.com/gorilla/mux - package: github.com/gorilla/context +- package: github.com/golang/glog diff --git a/vendor/github.com/golang/glog/LICENSE b/vendor/github.com/golang/glog/LICENSE new file mode 100644 index 0000000000..37ec93a14f --- /dev/null +++ b/vendor/github.com/golang/glog/LICENSE @@ -0,0 +1,191 @@ +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: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +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 +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. diff --git a/vendor/github.com/golang/glog/README b/vendor/github.com/golang/glog/README new file mode 100644 index 0000000000..387b4eb689 --- /dev/null +++ b/vendor/github.com/golang/glog/README @@ -0,0 +1,44 @@ +glog +==== + +Leveled execution logs for Go. + +This is an efficient pure Go implementation of leveled logs in the +manner of the open source C++ package + https://github.com/google/glog + +By binding methods to booleans it is possible to use the log package +without paying the expense of evaluating the arguments to the log. +Through the -vmodule flag, the package also provides fine-grained +control over logging at the file level. + +The comment from glog.go introduces the ideas: + + Package glog implements logging analogous to the Google-internal + C++ INFO/ERROR/V setup. It provides functions Info, Warning, + Error, Fatal, plus formatting variants such as Infof. It + also provides V-style logging controlled by the -v and + -vmodule=file=2 flags. + + Basic examples: + + glog.Info("Prepare to repel boarders") + + glog.Fatalf("Initialization failed: %s", err) + + See the documentation for the V function for an explanation + of these examples: + + if glog.V(2) { + glog.Info("Starting transaction...") + } + + glog.V(2).Infoln("Processed", nItems, "elements") + + +The repository contains an open source version of the log package +used inside Google. The master copy of the source lives inside +Google, not here. The code in this repo is for export only and is not itself +under development. Feature requests will be ignored. + +Send bug reports to golang-nuts@googlegroups.com. diff --git a/vendor/github.com/golang/glog/glog.go b/vendor/github.com/golang/glog/glog.go new file mode 100644 index 0000000000..54bd7afdca --- /dev/null +++ b/vendor/github.com/golang/glog/glog.go @@ -0,0 +1,1180 @@ +// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ +// +// Copyright 2013 Google Inc. All Rights Reserved. +// +// 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 glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. +// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as +// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. +// +// Basic examples: +// +// glog.Info("Prepare to repel boarders") +// +// glog.Fatalf("Initialization failed: %s", err) +// +// See the documentation for the V function for an explanation of these examples: +// +// if glog.V(2) { +// glog.Info("Starting transaction...") +// } +// +// glog.V(2).Infoln("Processed", nItems, "elements") +// +// Log output is buffered and written periodically using Flush. Programs +// should call Flush before exiting to guarantee all log output is written. +// +// By default, all log statements write to files in a temporary directory. +// This package provides several flags that modify this behavior. +// As a result, flag.Parse must be called before any logging is done. +// +// -logtostderr=false +// Logs are written to standard error instead of to files. +// -alsologtostderr=false +// Logs are written to standard error as well as to files. +// -stderrthreshold=ERROR +// Log events at or above this severity are logged to standard +// error as well as to files. +// -log_dir="" +// Log files will be written to this directory instead of the +// default temporary directory. +// +// Other flags provide aids to debugging. +// +// -log_backtrace_at="" +// When set to a file and line number holding a logging statement, +// such as +// -log_backtrace_at=gopherflakes.go:234 +// a stack trace will be written to the Info log whenever execution +// hits that statement. (Unlike with -vmodule, the ".go" must be +// present.) +// -v=0 +// Enable V-leveled logging at the specified level. +// -vmodule="" +// The syntax of the argument is a comma-separated list of pattern=N, +// where pattern is a literal file name (minus the ".go" suffix) or +// "glob" pattern and N is a V level. For instance, +// -vmodule=gopher*=3 +// sets the V level to 3 in all Go files whose names begin "gopher". +// +package glog + +import ( + "bufio" + "bytes" + "errors" + "flag" + "fmt" + "io" + stdLog "log" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// severity identifies the sort of log: info, warning etc. It also implements +// the flag.Value interface. The -stderrthreshold flag is of type severity and +// should be modified only through the flag.Value interface. The values match +// the corresponding constants in C++. +type severity int32 // sync/atomic int32 + +// These constants identify the log levels in order of increasing severity. +// A message written to a high-severity log file is also written to each +// lower-severity log file. +const ( + infoLog severity = iota + warningLog + errorLog + fatalLog + numSeverity = 4 +) + +const severityChar = "IWEF" + +var severityName = []string{ + infoLog: "INFO", + warningLog: "WARNING", + errorLog: "ERROR", + fatalLog: "FATAL", +} + +// get returns the value of the severity. +func (s *severity) get() severity { + return severity(atomic.LoadInt32((*int32)(s))) +} + +// set sets the value of the severity. +func (s *severity) set(val severity) { + atomic.StoreInt32((*int32)(s), int32(val)) +} + +// String is part of the flag.Value interface. +func (s *severity) String() string { + return strconv.FormatInt(int64(*s), 10) +} + +// Get is part of the flag.Value interface. +func (s *severity) Get() interface{} { + return *s +} + +// Set is part of the flag.Value interface. +func (s *severity) Set(value string) error { + var threshold severity + // Is it a known name? + if v, ok := severityByName(value); ok { + threshold = v + } else { + v, err := strconv.Atoi(value) + if err != nil { + return err + } + threshold = severity(v) + } + logging.stderrThreshold.set(threshold) + return nil +} + +func severityByName(s string) (severity, bool) { + s = strings.ToUpper(s) + for i, name := range severityName { + if name == s { + return severity(i), true + } + } + return 0, false +} + +// OutputStats tracks the number of output lines and bytes written. +type OutputStats struct { + lines int64 + bytes int64 +} + +// Lines returns the number of lines written. +func (s *OutputStats) Lines() int64 { + return atomic.LoadInt64(&s.lines) +} + +// Bytes returns the number of bytes written. +func (s *OutputStats) Bytes() int64 { + return atomic.LoadInt64(&s.bytes) +} + +// Stats tracks the number of lines of output and number of bytes +// per severity level. Values must be read with atomic.LoadInt64. +var Stats struct { + Info, Warning, Error OutputStats +} + +var severityStats = [numSeverity]*OutputStats{ + infoLog: &Stats.Info, + warningLog: &Stats.Warning, + errorLog: &Stats.Error, +} + +// Level is exported because it appears in the arguments to V and is +// the type of the v flag, which can be set programmatically. +// It's a distinct type because we want to discriminate it from logType. +// Variables of type level are only changed under logging.mu. +// The -v flag is read only with atomic ops, so the state of the logging +// module is consistent. + +// Level is treated as a sync/atomic int32. + +// Level specifies a level of verbosity for V logs. *Level implements +// flag.Value; the -v flag is of type Level and should be modified +// only through the flag.Value interface. +type Level int32 + +// get returns the value of the Level. +func (l *Level) get() Level { + return Level(atomic.LoadInt32((*int32)(l))) +} + +// set sets the value of the Level. +func (l *Level) set(val Level) { + atomic.StoreInt32((*int32)(l), int32(val)) +} + +// String is part of the flag.Value interface. +func (l *Level) String() string { + return strconv.FormatInt(int64(*l), 10) +} + +// Get is part of the flag.Value interface. +func (l *Level) Get() interface{} { + return *l +} + +// Set is part of the flag.Value interface. +func (l *Level) Set(value string) error { + v, err := strconv.Atoi(value) + if err != nil { + return err + } + logging.mu.Lock() + defer logging.mu.Unlock() + logging.setVState(Level(v), logging.vmodule.filter, false) + return nil +} + +// moduleSpec represents the setting of the -vmodule flag. +type moduleSpec struct { + filter []modulePat +} + +// modulePat contains a filter for the -vmodule flag. +// It holds a verbosity level and a file pattern to match. +type modulePat struct { + pattern string + literal bool // The pattern is a literal string + level Level +} + +// match reports whether the file matches the pattern. It uses a string +// comparison if the pattern contains no metacharacters. +func (m *modulePat) match(file string) bool { + if m.literal { + return file == m.pattern + } + match, _ := filepath.Match(m.pattern, file) + return match +} + +func (m *moduleSpec) String() string { + // Lock because the type is not atomic. TODO: clean this up. + logging.mu.Lock() + defer logging.mu.Unlock() + var b bytes.Buffer + for i, f := range m.filter { + if i > 0 { + b.WriteRune(',') + } + fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) + } + return b.String() +} + +// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the +// struct is not exported. +func (m *moduleSpec) Get() interface{} { + return nil +} + +var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") + +// Syntax: -vmodule=recordio=2,file=1,gfs*=3 +func (m *moduleSpec) Set(value string) error { + var filter []modulePat + for _, pat := range strings.Split(value, ",") { + if len(pat) == 0 { + // Empty strings such as from a trailing comma can be ignored. + continue + } + patLev := strings.Split(pat, "=") + if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { + return errVmoduleSyntax + } + pattern := patLev[0] + v, err := strconv.Atoi(patLev[1]) + if err != nil { + return errors.New("syntax error: expect comma-separated list of filename=N") + } + if v < 0 { + return errors.New("negative value for vmodule level") + } + if v == 0 { + continue // Ignore. It's harmless but no point in paying the overhead. + } + // TODO: check syntax of filter? + filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) + } + logging.mu.Lock() + defer logging.mu.Unlock() + logging.setVState(logging.verbosity, filter, true) + return nil +} + +// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters +// that require filepath.Match to be called to match the pattern. +func isLiteral(pattern string) bool { + return !strings.ContainsAny(pattern, `\*?[]`) +} + +// traceLocation represents the setting of the -log_backtrace_at flag. +type traceLocation struct { + file string + line int +} + +// isSet reports whether the trace location has been specified. +// logging.mu is held. +func (t *traceLocation) isSet() bool { + return t.line > 0 +} + +// match reports whether the specified file and line matches the trace location. +// The argument file name is the full path, not the basename specified in the flag. +// logging.mu is held. +func (t *traceLocation) match(file string, line int) bool { + if t.line != line { + return false + } + if i := strings.LastIndex(file, "/"); i >= 0 { + file = file[i+1:] + } + return t.file == file +} + +func (t *traceLocation) String() string { + // Lock because the type is not atomic. TODO: clean this up. + logging.mu.Lock() + defer logging.mu.Unlock() + return fmt.Sprintf("%s:%d", t.file, t.line) +} + +// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the +// struct is not exported +func (t *traceLocation) Get() interface{} { + return nil +} + +var errTraceSyntax = errors.New("syntax error: expect file.go:234") + +// Syntax: -log_backtrace_at=gopherflakes.go:234 +// Note that unlike vmodule the file extension is included here. +func (t *traceLocation) Set(value string) error { + if value == "" { + // Unset. + t.line = 0 + t.file = "" + } + fields := strings.Split(value, ":") + if len(fields) != 2 { + return errTraceSyntax + } + file, line := fields[0], fields[1] + if !strings.Contains(file, ".") { + return errTraceSyntax + } + v, err := strconv.Atoi(line) + if err != nil { + return errTraceSyntax + } + if v <= 0 { + return errors.New("negative or zero value for level") + } + logging.mu.Lock() + defer logging.mu.Unlock() + t.line = v + t.file = file + return nil +} + +// flushSyncWriter is the interface satisfied by logging destinations. +type flushSyncWriter interface { + Flush() error + Sync() error + io.Writer +} + +func init() { + flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files") + flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") + flag.Var(&logging.verbosity, "v", "log level for V logs") + flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") + flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") + flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") + + // Default stderrThreshold is ERROR. + logging.stderrThreshold = errorLog + + logging.setVState(0, nil, false) + go logging.flushDaemon() +} + +// Flush flushes all pending log I/O. +func Flush() { + logging.lockAndFlushAll() +} + +// loggingT collects all the global state of the logging setup. +type loggingT struct { + // Boolean flags. Not handled atomically because the flag.Value interface + // does not let us avoid the =true, and that shorthand is necessary for + // compatibility. TODO: does this matter enough to fix? Seems unlikely. + toStderr bool // The -logtostderr flag. + alsoToStderr bool // The -alsologtostderr flag. + + // Level flag. Handled atomically. + stderrThreshold severity // The -stderrthreshold flag. + + // freeList is a list of byte buffers, maintained under freeListMu. + freeList *buffer + // freeListMu maintains the free list. It is separate from the main mutex + // so buffers can be grabbed and printed to without holding the main lock, + // for better parallelization. + freeListMu sync.Mutex + + // mu protects the remaining elements of this structure and is + // used to synchronize logging. + mu sync.Mutex + // file holds writer for each of the log types. + file [numSeverity]flushSyncWriter + // pcs is used in V to avoid an allocation when computing the caller's PC. + pcs [1]uintptr + // vmap is a cache of the V Level for each V() call site, identified by PC. + // It is wiped whenever the vmodule flag changes state. + vmap map[uintptr]Level + // filterLength stores the length of the vmodule filter chain. If greater + // than zero, it means vmodule is enabled. It may be read safely + // using sync.LoadInt32, but is only modified under mu. + filterLength int32 + // traceLocation is the state of the -log_backtrace_at flag. + traceLocation traceLocation + // These flags are modified only under lock, although verbosity may be fetched + // safely using atomic.LoadInt32. + vmodule moduleSpec // The state of the -vmodule flag. + verbosity Level // V logging level, the value of the -v flag/ +} + +// buffer holds a byte Buffer for reuse. The zero value is ready for use. +type buffer struct { + bytes.Buffer + tmp [64]byte // temporary byte array for creating headers. + next *buffer +} + +var logging loggingT + +// setVState sets a consistent state for V logging. +// l.mu is held. +func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { + // Turn verbosity off so V will not fire while we are in transition. + logging.verbosity.set(0) + // Ditto for filter length. + atomic.StoreInt32(&logging.filterLength, 0) + + // Set the new filters and wipe the pc->Level map if the filter has changed. + if setFilter { + logging.vmodule.filter = filter + logging.vmap = make(map[uintptr]Level) + } + + // Things are consistent now, so enable filtering and verbosity. + // They are enabled in order opposite to that in V. + atomic.StoreInt32(&logging.filterLength, int32(len(filter))) + logging.verbosity.set(verbosity) +} + +// getBuffer returns a new, ready-to-use buffer. +func (l *loggingT) getBuffer() *buffer { + l.freeListMu.Lock() + b := l.freeList + if b != nil { + l.freeList = b.next + } + l.freeListMu.Unlock() + if b == nil { + b = new(buffer) + } else { + b.next = nil + b.Reset() + } + return b +} + +// putBuffer returns a buffer to the free list. +func (l *loggingT) putBuffer(b *buffer) { + if b.Len() >= 256 { + // Let big buffers die a natural death. + return + } + l.freeListMu.Lock() + b.next = l.freeList + l.freeList = b + l.freeListMu.Unlock() +} + +var timeNow = time.Now // Stubbed out for testing. + +/* +header formats a log header as defined by the C++ implementation. +It returns a buffer containing the formatted header and the user's file and line number. +The depth specifies how many stack frames above lives the source line to be identified in the log message. + +Log lines have this form: + Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... +where the fields are defined as follows: + L A single character, representing the log level (eg 'I' for INFO) + mm The month (zero padded; ie May is '05') + dd The day (zero padded) + hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds + threadid The space-padded thread ID as returned by GetTID() + file The file name + line The line number + msg The user-supplied message +*/ +func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { + _, file, line, ok := runtime.Caller(3 + depth) + if !ok { + file = "???" + line = 1 + } else { + slash := strings.LastIndex(file, "/") + if slash >= 0 { + file = file[slash+1:] + } + } + return l.formatHeader(s, file, line), file, line +} + +// formatHeader formats a log header using the provided file name and line number. +func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { + now := timeNow() + if line < 0 { + line = 0 // not a real line number, but acceptable to someDigits + } + if s > fatalLog { + s = infoLog // for safety. + } + buf := l.getBuffer() + + // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. + // It's worth about 3X. Fprintf is hard. + _, month, day := now.Date() + hour, minute, second := now.Clock() + // Lmmdd hh:mm:ss.uuuuuu threadid file:line] + buf.tmp[0] = severityChar[s] + buf.twoDigits(1, int(month)) + buf.twoDigits(3, day) + buf.tmp[5] = ' ' + buf.twoDigits(6, hour) + buf.tmp[8] = ':' + buf.twoDigits(9, minute) + buf.tmp[11] = ':' + buf.twoDigits(12, second) + buf.tmp[14] = '.' + buf.nDigits(6, 15, now.Nanosecond()/1000, '0') + buf.tmp[21] = ' ' + buf.nDigits(7, 22, pid, ' ') // TODO: should be TID + buf.tmp[29] = ' ' + buf.Write(buf.tmp[:30]) + buf.WriteString(file) + buf.tmp[0] = ':' + n := buf.someDigits(1, line) + buf.tmp[n+1] = ']' + buf.tmp[n+2] = ' ' + buf.Write(buf.tmp[:n+3]) + return buf +} + +// Some custom tiny helper functions to print the log header efficiently. + +const digits = "0123456789" + +// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. +func (buf *buffer) twoDigits(i, d int) { + buf.tmp[i+1] = digits[d%10] + d /= 10 + buf.tmp[i] = digits[d%10] +} + +// nDigits formats an n-digit integer at buf.tmp[i], +// padding with pad on the left. +// It assumes d >= 0. +func (buf *buffer) nDigits(n, i, d int, pad byte) { + j := n - 1 + for ; j >= 0 && d > 0; j-- { + buf.tmp[i+j] = digits[d%10] + d /= 10 + } + for ; j >= 0; j-- { + buf.tmp[i+j] = pad + } +} + +// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. +func (buf *buffer) someDigits(i, d int) int { + // Print into the top, then copy down. We know there's space for at least + // a 10-digit number. + j := len(buf.tmp) + for { + j-- + buf.tmp[j] = digits[d%10] + d /= 10 + if d == 0 { + break + } + } + return copy(buf.tmp[i:], buf.tmp[j:]) +} + +func (l *loggingT) println(s severity, args ...interface{}) { + buf, file, line := l.header(s, 0) + fmt.Fprintln(buf, args...) + l.output(s, buf, file, line, false) +} + +func (l *loggingT) print(s severity, args ...interface{}) { + l.printDepth(s, 1, args...) +} + +func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { + buf, file, line := l.header(s, depth) + fmt.Fprint(buf, args...) + if buf.Bytes()[buf.Len()-1] != '\n' { + buf.WriteByte('\n') + } + l.output(s, buf, file, line, false) +} + +func (l *loggingT) printf(s severity, format string, args ...interface{}) { + buf, file, line := l.header(s, 0) + fmt.Fprintf(buf, format, args...) + if buf.Bytes()[buf.Len()-1] != '\n' { + buf.WriteByte('\n') + } + l.output(s, buf, file, line, false) +} + +// printWithFileLine behaves like print but uses the provided file and line number. If +// alsoLogToStderr is true, the log message always appears on standard error; it +// will also appear in the log file unless --logtostderr is set. +func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { + buf := l.formatHeader(s, file, line) + fmt.Fprint(buf, args...) + if buf.Bytes()[buf.Len()-1] != '\n' { + buf.WriteByte('\n') + } + l.output(s, buf, file, line, alsoToStderr) +} + +// output writes the data to the log files and releases the buffer. +func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { + l.mu.Lock() + if l.traceLocation.isSet() { + if l.traceLocation.match(file, line) { + buf.Write(stacks(false)) + } + } + data := buf.Bytes() + if !flag.Parsed() { + os.Stderr.Write([]byte("ERROR: logging before flag.Parse: ")) + os.Stderr.Write(data) + } else if l.toStderr { + os.Stderr.Write(data) + } else { + if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { + os.Stderr.Write(data) + } + if l.file[s] == nil { + if err := l.createFiles(s); err != nil { + os.Stderr.Write(data) // Make sure the message appears somewhere. + l.exit(err) + } + } + switch s { + case fatalLog: + l.file[fatalLog].Write(data) + fallthrough + case errorLog: + l.file[errorLog].Write(data) + fallthrough + case warningLog: + l.file[warningLog].Write(data) + fallthrough + case infoLog: + l.file[infoLog].Write(data) + } + } + if s == fatalLog { + // If we got here via Exit rather than Fatal, print no stacks. + if atomic.LoadUint32(&fatalNoStacks) > 0 { + l.mu.Unlock() + timeoutFlush(10 * time.Second) + os.Exit(1) + } + // Dump all goroutine stacks before exiting. + // First, make sure we see the trace for the current goroutine on standard error. + // If -logtostderr has been specified, the loop below will do that anyway + // as the first stack in the full dump. + if !l.toStderr { + os.Stderr.Write(stacks(false)) + } + // Write the stack trace for all goroutines to the files. + trace := stacks(true) + logExitFunc = func(error) {} // If we get a write error, we'll still exit below. + for log := fatalLog; log >= infoLog; log-- { + if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. + f.Write(trace) + } + } + l.mu.Unlock() + timeoutFlush(10 * time.Second) + os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. + } + l.putBuffer(buf) + l.mu.Unlock() + if stats := severityStats[s]; stats != nil { + atomic.AddInt64(&stats.lines, 1) + atomic.AddInt64(&stats.bytes, int64(len(data))) + } +} + +// timeoutFlush calls Flush and returns when it completes or after timeout +// elapses, whichever happens first. This is needed because the hooks invoked +// by Flush may deadlock when glog.Fatal is called from a hook that holds +// a lock. +func timeoutFlush(timeout time.Duration) { + done := make(chan bool, 1) + go func() { + Flush() // calls logging.lockAndFlushAll() + done <- true + }() + select { + case <-done: + case <-time.After(timeout): + fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) + } +} + +// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. +func stacks(all bool) []byte { + // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. + n := 10000 + if all { + n = 100000 + } + var trace []byte + for i := 0; i < 5; i++ { + trace = make([]byte, n) + nbytes := runtime.Stack(trace, all) + if nbytes < len(trace) { + return trace[:nbytes] + } + n *= 2 + } + return trace +} + +// logExitFunc provides a simple mechanism to override the default behavior +// of exiting on error. Used in testing and to guarantee we reach a required exit +// for fatal logs. Instead, exit could be a function rather than a method but that +// would make its use clumsier. +var logExitFunc func(error) + +// exit is called if there is trouble creating or writing log files. +// It flushes the logs and exits the program; there's no point in hanging around. +// l.mu is held. +func (l *loggingT) exit(err error) { + fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) + // If logExitFunc is set, we do that instead of exiting. + if logExitFunc != nil { + logExitFunc(err) + return + } + l.flushAll() + os.Exit(2) +} + +// syncBuffer joins a bufio.Writer to its underlying file, providing access to the +// file's Sync method and providing a wrapper for the Write method that provides log +// file rotation. There are conflicting methods, so the file cannot be embedded. +// l.mu is held for all its methods. +type syncBuffer struct { + logger *loggingT + *bufio.Writer + file *os.File + sev severity + nbytes uint64 // The number of bytes written to this file +} + +func (sb *syncBuffer) Sync() error { + return sb.file.Sync() +} + +func (sb *syncBuffer) Write(p []byte) (n int, err error) { + if sb.nbytes+uint64(len(p)) >= MaxSize { + if err := sb.rotateFile(time.Now()); err != nil { + sb.logger.exit(err) + } + } + n, err = sb.Writer.Write(p) + sb.nbytes += uint64(n) + if err != nil { + sb.logger.exit(err) + } + return +} + +// rotateFile closes the syncBuffer's file and starts a new one. +func (sb *syncBuffer) rotateFile(now time.Time) error { + if sb.file != nil { + sb.Flush() + sb.file.Close() + } + var err error + sb.file, _, err = create(severityName[sb.sev], now) + sb.nbytes = 0 + if err != nil { + return err + } + + sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) + + // Write header. + var buf bytes.Buffer + fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) + fmt.Fprintf(&buf, "Running on machine: %s\n", host) + fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) + fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") + n, err := sb.file.Write(buf.Bytes()) + sb.nbytes += uint64(n) + return err +} + +// bufferSize sizes the buffer associated with each log file. It's large +// so that log records can accumulate without the logging thread blocking +// on disk I/O. The flushDaemon will block instead. +const bufferSize = 256 * 1024 + +// createFiles creates all the log files for severity from sev down to infoLog. +// l.mu is held. +func (l *loggingT) createFiles(sev severity) error { + now := time.Now() + // Files are created in decreasing severity order, so as soon as we find one + // has already been created, we can stop. + for s := sev; s >= infoLog && l.file[s] == nil; s-- { + sb := &syncBuffer{ + logger: l, + sev: s, + } + if err := sb.rotateFile(now); err != nil { + return err + } + l.file[s] = sb + } + return nil +} + +const flushInterval = 30 * time.Second + +// flushDaemon periodically flushes the log file buffers. +func (l *loggingT) flushDaemon() { + for _ = range time.NewTicker(flushInterval).C { + l.lockAndFlushAll() + } +} + +// lockAndFlushAll is like flushAll but locks l.mu first. +func (l *loggingT) lockAndFlushAll() { + l.mu.Lock() + l.flushAll() + l.mu.Unlock() +} + +// flushAll flushes all the logs and attempts to "sync" their data to disk. +// l.mu is held. +func (l *loggingT) flushAll() { + // Flush from fatal down, in case there's trouble flushing. + for s := fatalLog; s >= infoLog; s-- { + file := l.file[s] + if file != nil { + file.Flush() // ignore error + file.Sync() // ignore error + } + } +} + +// CopyStandardLogTo arranges for messages written to the Go "log" package's +// default logs to also appear in the Google logs for the named and lower +// severities. Subsequent changes to the standard log's default output location +// or format may break this behavior. +// +// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not +// recognized, CopyStandardLogTo panics. +func CopyStandardLogTo(name string) { + sev, ok := severityByName(name) + if !ok { + panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) + } + // Set a log format that captures the user's file and line: + // d.go:23: message + stdLog.SetFlags(stdLog.Lshortfile) + stdLog.SetOutput(logBridge(sev)) +} + +// logBridge provides the Write method that enables CopyStandardLogTo to connect +// Go's standard logs to the logs provided by this package. +type logBridge severity + +// Write parses the standard logging line and passes its components to the +// logger for severity(lb). +func (lb logBridge) Write(b []byte) (n int, err error) { + var ( + file = "???" + line = 1 + text string + ) + // Split "d.go:23: message" into "d.go", "23", and "message". + if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { + text = fmt.Sprintf("bad log format: %s", b) + } else { + file = string(parts[0]) + text = string(parts[2][1:]) // skip leading space + line, err = strconv.Atoi(string(parts[1])) + if err != nil { + text = fmt.Sprintf("bad line number: %s", b) + line = 1 + } + } + // printWithFileLine with alsoToStderr=true, so standard log messages + // always appear on standard error. + logging.printWithFileLine(severity(lb), file, line, true, text) + return len(b), nil +} + +// setV computes and remembers the V level for a given PC +// when vmodule is enabled. +// File pattern matching takes the basename of the file, stripped +// of its .go suffix, and uses filepath.Match, which is a little more +// general than the *? matching used in C++. +// l.mu is held. +func (l *loggingT) setV(pc uintptr) Level { + fn := runtime.FuncForPC(pc) + file, _ := fn.FileLine(pc) + // The file is something like /a/b/c/d.go. We want just the d. + if strings.HasSuffix(file, ".go") { + file = file[:len(file)-3] + } + if slash := strings.LastIndex(file, "/"); slash >= 0 { + file = file[slash+1:] + } + for _, filter := range l.vmodule.filter { + if filter.match(file) { + l.vmap[pc] = filter.level + return filter.level + } + } + l.vmap[pc] = 0 + return 0 +} + +// Verbose is a boolean type that implements Infof (like Printf) etc. +// See the documentation of V for more information. +type Verbose bool + +// V reports whether verbosity at the call site is at least the requested level. +// The returned value is a boolean of type Verbose, which implements Info, Infoln +// and Infof. These methods will write to the Info log if called. +// Thus, one may write either +// if glog.V(2) { glog.Info("log this") } +// or +// glog.V(2).Info("log this") +// The second form is shorter but the first is cheaper if logging is off because it does +// not evaluate its arguments. +// +// Whether an individual call to V generates a log record depends on the setting of +// the -v and --vmodule flags; both are off by default. If the level in the call to +// V is at least the value of -v, or of -vmodule for the source file containing the +// call, the V call will log. +func V(level Level) Verbose { + // This function tries hard to be cheap unless there's work to do. + // The fast path is two atomic loads and compares. + + // Here is a cheap but safe test to see if V logging is enabled globally. + if logging.verbosity.get() >= level { + return Verbose(true) + } + + // It's off globally but it vmodule may still be set. + // Here is another cheap but safe test to see if vmodule is enabled. + if atomic.LoadInt32(&logging.filterLength) > 0 { + // Now we need a proper lock to use the logging structure. The pcs field + // is shared so we must lock before accessing it. This is fairly expensive, + // but if V logging is enabled we're slow anyway. + logging.mu.Lock() + defer logging.mu.Unlock() + if runtime.Callers(2, logging.pcs[:]) == 0 { + return Verbose(false) + } + v, ok := logging.vmap[logging.pcs[0]] + if !ok { + v = logging.setV(logging.pcs[0]) + } + return Verbose(v >= level) + } + return Verbose(false) +} + +// Info is equivalent to the global Info function, guarded by the value of v. +// See the documentation of V for usage. +func (v Verbose) Info(args ...interface{}) { + if v { + logging.print(infoLog, args...) + } +} + +// Infoln is equivalent to the global Infoln function, guarded by the value of v. +// See the documentation of V for usage. +func (v Verbose) Infoln(args ...interface{}) { + if v { + logging.println(infoLog, args...) + } +} + +// Infof is equivalent to the global Infof function, guarded by the value of v. +// See the documentation of V for usage. +func (v Verbose) Infof(format string, args ...interface{}) { + if v { + logging.printf(infoLog, format, args...) + } +} + +// Info logs to the INFO log. +// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. +func Info(args ...interface{}) { + logging.print(infoLog, args...) +} + +// InfoDepth acts as Info but uses depth to determine which call frame to log. +// InfoDepth(0, "msg") is the same as Info("msg"). +func InfoDepth(depth int, args ...interface{}) { + logging.printDepth(infoLog, depth, args...) +} + +// Infoln logs to the INFO log. +// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +func Infoln(args ...interface{}) { + logging.println(infoLog, args...) +} + +// Infof logs to the INFO log. +// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. +func Infof(format string, args ...interface{}) { + logging.printf(infoLog, format, args...) +} + +// Warning logs to the WARNING and INFO logs. +// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. +func Warning(args ...interface{}) { + logging.print(warningLog, args...) +} + +// WarningDepth acts as Warning but uses depth to determine which call frame to log. +// WarningDepth(0, "msg") is the same as Warning("msg"). +func WarningDepth(depth int, args ...interface{}) { + logging.printDepth(warningLog, depth, args...) +} + +// Warningln logs to the WARNING and INFO logs. +// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +func Warningln(args ...interface{}) { + logging.println(warningLog, args...) +} + +// Warningf logs to the WARNING and INFO logs. +// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. +func Warningf(format string, args ...interface{}) { + logging.printf(warningLog, format, args...) +} + +// Error logs to the ERROR, WARNING, and INFO logs. +// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. +func Error(args ...interface{}) { + logging.print(errorLog, args...) +} + +// ErrorDepth acts as Error but uses depth to determine which call frame to log. +// ErrorDepth(0, "msg") is the same as Error("msg"). +func ErrorDepth(depth int, args ...interface{}) { + logging.printDepth(errorLog, depth, args...) +} + +// Errorln logs to the ERROR, WARNING, and INFO logs. +// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +func Errorln(args ...interface{}) { + logging.println(errorLog, args...) +} + +// Errorf logs to the ERROR, WARNING, and INFO logs. +// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. +func Errorf(format string, args ...interface{}) { + logging.printf(errorLog, format, args...) +} + +// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, +// including a stack trace of all running goroutines, then calls os.Exit(255). +// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. +func Fatal(args ...interface{}) { + logging.print(fatalLog, args...) +} + +// FatalDepth acts as Fatal but uses depth to determine which call frame to log. +// FatalDepth(0, "msg") is the same as Fatal("msg"). +func FatalDepth(depth int, args ...interface{}) { + logging.printDepth(fatalLog, depth, args...) +} + +// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, +// including a stack trace of all running goroutines, then calls os.Exit(255). +// Arguments are handled in the manner of fmt.Println; a newline is appended if missing. +func Fatalln(args ...interface{}) { + logging.println(fatalLog, args...) +} + +// Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, +// including a stack trace of all running goroutines, then calls os.Exit(255). +// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. +func Fatalf(format string, args ...interface{}) { + logging.printf(fatalLog, format, args...) +} + +// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. +// It allows Exit and relatives to use the Fatal logs. +var fatalNoStacks uint32 + +// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). +// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. +func Exit(args ...interface{}) { + atomic.StoreUint32(&fatalNoStacks, 1) + logging.print(fatalLog, args...) +} + +// ExitDepth acts as Exit but uses depth to determine which call frame to log. +// ExitDepth(0, "msg") is the same as Exit("msg"). +func ExitDepth(depth int, args ...interface{}) { + atomic.StoreUint32(&fatalNoStacks, 1) + logging.printDepth(fatalLog, depth, args...) +} + +// Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). +func Exitln(args ...interface{}) { + atomic.StoreUint32(&fatalNoStacks, 1) + logging.println(fatalLog, args...) +} + +// Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). +// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. +func Exitf(format string, args ...interface{}) { + atomic.StoreUint32(&fatalNoStacks, 1) + logging.printf(fatalLog, format, args...) +} diff --git a/vendor/github.com/golang/glog/glog_file.go b/vendor/github.com/golang/glog/glog_file.go new file mode 100644 index 0000000000..65075d2811 --- /dev/null +++ b/vendor/github.com/golang/glog/glog_file.go @@ -0,0 +1,124 @@ +// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ +// +// Copyright 2013 Google Inc. All Rights Reserved. +// +// 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. + +// File I/O for logs. + +package glog + +import ( + "errors" + "flag" + "fmt" + "os" + "os/user" + "path/filepath" + "strings" + "sync" + "time" +) + +// MaxSize is the maximum size of a log file in bytes. +var MaxSize uint64 = 1024 * 1024 * 1800 + +// logDirs lists the candidate directories for new log files. +var logDirs []string + +// If non-empty, overrides the choice of directory in which to write logs. +// See createLogDirs for the full list of possible destinations. +var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") + +func createLogDirs() { + if *logDir != "" { + logDirs = append(logDirs, *logDir) + } + logDirs = append(logDirs, os.TempDir()) +} + +var ( + pid = os.Getpid() + program = filepath.Base(os.Args[0]) + host = "unknownhost" + userName = "unknownuser" +) + +func init() { + h, err := os.Hostname() + if err == nil { + host = shortHostname(h) + } + + current, err := user.Current() + if err == nil { + userName = current.Username + } + + // Sanitize userName since it may contain filepath separators on Windows. + userName = strings.Replace(userName, `\`, "_", -1) +} + +// shortHostname returns its argument, truncating at the first period. +// For instance, given "www.google.com" it returns "www". +func shortHostname(hostname string) string { + if i := strings.Index(hostname, "."); i >= 0 { + return hostname[:i] + } + return hostname +} + +// logName returns a new log file name containing tag, with start time t, and +// the name for the symlink for tag. +func logName(tag string, t time.Time) (name, link string) { + name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", + program, + host, + userName, + tag, + t.Year(), + t.Month(), + t.Day(), + t.Hour(), + t.Minute(), + t.Second(), + pid) + return name, program + "." + tag +} + +var onceLogDirs sync.Once + +// create creates a new log file and returns the file and its filename, which +// contains tag ("INFO", "FATAL", etc.) and t. If the file is created +// successfully, create also attempts to update the symlink for that tag, ignoring +// errors. +func create(tag string, t time.Time) (f *os.File, filename string, err error) { + onceLogDirs.Do(createLogDirs) + if len(logDirs) == 0 { + return nil, "", errors.New("log: no log dirs") + } + name, link := logName(tag, t) + var lastErr error + for _, dir := range logDirs { + fname := filepath.Join(dir, name) + f, err := os.Create(fname) + if err == nil { + symlink := filepath.Join(dir, link) + os.Remove(symlink) // ignore err + os.Symlink(name, symlink) // ignore err + return f, fname, nil + } + lastErr = err + } + return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) +} diff --git a/vendor/github.com/golang/glog/glog_test.go b/vendor/github.com/golang/glog/glog_test.go new file mode 100644 index 0000000000..0fb376e1fd --- /dev/null +++ b/vendor/github.com/golang/glog/glog_test.go @@ -0,0 +1,415 @@ +// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ +// +// Copyright 2013 Google Inc. All Rights Reserved. +// +// 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 glog + +import ( + "bytes" + "fmt" + stdLog "log" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" +) + +// Test that shortHostname works as advertised. +func TestShortHostname(t *testing.T) { + for hostname, expect := range map[string]string{ + "": "", + "host": "host", + "host.google.com": "host", + } { + if got := shortHostname(hostname); expect != got { + t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) + } + } +} + +// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. +type flushBuffer struct { + bytes.Buffer +} + +func (f *flushBuffer) Flush() error { + return nil +} + +func (f *flushBuffer) Sync() error { + return nil +} + +// swap sets the log writers and returns the old array. +func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { + l.mu.Lock() + defer l.mu.Unlock() + old = l.file + for i, w := range writers { + logging.file[i] = w + } + return +} + +// newBuffers sets the log writers to all new byte buffers and returns the old array. +func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { + return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) +} + +// contents returns the specified log value as a string. +func contents(s severity) string { + return logging.file[s].(*flushBuffer).String() +} + +// contains reports whether the string is contained in the log. +func contains(s severity, str string, t *testing.T) bool { + return strings.Contains(contents(s), str) +} + +// setFlags configures the logging flags how the test expects them. +func setFlags() { + logging.toStderr = false +} + +// Test that Info works as advertised. +func TestInfo(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + Info("test") + if !contains(infoLog, "I", t) { + t.Errorf("Info has wrong character: %q", contents(infoLog)) + } + if !contains(infoLog, "test", t) { + t.Error("Info failed") + } +} + +func TestInfoDepth(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + + f := func() { InfoDepth(1, "depth-test1") } + + // The next three lines must stay together + _, _, wantLine, _ := runtime.Caller(0) + InfoDepth(0, "depth-test0") + f() + + msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") + if len(msgs) != 2 { + t.Fatalf("Got %d lines, expected 2", len(msgs)) + } + + for i, m := range msgs { + if !strings.HasPrefix(m, "I") { + t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) + } + w := fmt.Sprintf("depth-test%d", i) + if !strings.Contains(m, w) { + t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) + } + + // pull out the line number (between : and ]) + msg := m[strings.LastIndex(m, ":")+1:] + x := strings.Index(msg, "]") + if x < 0 { + t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) + continue + } + line, err := strconv.Atoi(msg[:x]) + if err != nil { + t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) + continue + } + wantLine++ + if wantLine != line { + t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) + } + } +} + +func init() { + CopyStandardLogTo("INFO") +} + +// Test that CopyStandardLogTo panics on bad input. +func TestCopyStandardLogToPanic(t *testing.T) { + defer func() { + if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { + t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) + } + }() + CopyStandardLogTo("LOG") +} + +// Test that using the standard log package logs to INFO. +func TestStandardLog(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + stdLog.Print("test") + if !contains(infoLog, "I", t) { + t.Errorf("Info has wrong character: %q", contents(infoLog)) + } + if !contains(infoLog, "test", t) { + t.Error("Info failed") + } +} + +// Test that the header has the correct format. +func TestHeader(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + defer func(previous func() time.Time) { timeNow = previous }(timeNow) + timeNow = func() time.Time { + return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) + } + pid = 1234 + Info("test") + var line int + format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" + n, err := fmt.Sscanf(contents(infoLog), format, &line) + if n != 1 || err != nil { + t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) + } + // Scanf treats multiple spaces as equivalent to a single space, + // so check for correct space-padding also. + want := fmt.Sprintf(format, line) + if contents(infoLog) != want { + t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) + } +} + +// Test that an Error log goes to Warning and Info. +// Even in the Info log, the source character will be E, so the data should +// all be identical. +func TestError(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + Error("test") + if !contains(errorLog, "E", t) { + t.Errorf("Error has wrong character: %q", contents(errorLog)) + } + if !contains(errorLog, "test", t) { + t.Error("Error failed") + } + str := contents(errorLog) + if !contains(warningLog, str, t) { + t.Error("Warning failed") + } + if !contains(infoLog, str, t) { + t.Error("Info failed") + } +} + +// Test that a Warning log goes to Info. +// Even in the Info log, the source character will be W, so the data should +// all be identical. +func TestWarning(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + Warning("test") + if !contains(warningLog, "W", t) { + t.Errorf("Warning has wrong character: %q", contents(warningLog)) + } + if !contains(warningLog, "test", t) { + t.Error("Warning failed") + } + str := contents(warningLog) + if !contains(infoLog, str, t) { + t.Error("Info failed") + } +} + +// Test that a V log goes to Info. +func TestV(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + logging.verbosity.Set("2") + defer logging.verbosity.Set("0") + V(2).Info("test") + if !contains(infoLog, "I", t) { + t.Errorf("Info has wrong character: %q", contents(infoLog)) + } + if !contains(infoLog, "test", t) { + t.Error("Info failed") + } +} + +// Test that a vmodule enables a log in this file. +func TestVmoduleOn(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + logging.vmodule.Set("glog_test=2") + defer logging.vmodule.Set("") + if !V(1) { + t.Error("V not enabled for 1") + } + if !V(2) { + t.Error("V not enabled for 2") + } + if V(3) { + t.Error("V enabled for 3") + } + V(2).Info("test") + if !contains(infoLog, "I", t) { + t.Errorf("Info has wrong character: %q", contents(infoLog)) + } + if !contains(infoLog, "test", t) { + t.Error("Info failed") + } +} + +// Test that a vmodule of another file does not enable a log in this file. +func TestVmoduleOff(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + logging.vmodule.Set("notthisfile=2") + defer logging.vmodule.Set("") + for i := 1; i <= 3; i++ { + if V(Level(i)) { + t.Errorf("V enabled for %d", i) + } + } + V(2).Info("test") + if contents(infoLog) != "" { + t.Error("V logged incorrectly") + } +} + +// vGlobs are patterns that match/don't match this file at V=2. +var vGlobs = map[string]bool{ + // Easy to test the numeric match here. + "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. + "glog_test=2": true, + "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. + // These all use 2 and check the patterns. All are true. + "*=2": true, + "?l*=2": true, + "????_*=2": true, + "??[mno]?_*t=2": true, + // These all use 2 and check the patterns. All are false. + "*x=2": false, + "m*=2": false, + "??_*=2": false, + "?[abc]?_*t=2": false, +} + +// Test that vmodule globbing works as advertised. +func testVmoduleGlob(pat string, match bool, t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + defer logging.vmodule.Set("") + logging.vmodule.Set(pat) + if V(2) != Verbose(match) { + t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) + } +} + +// Test that a vmodule globbing works as advertised. +func TestVmoduleGlob(t *testing.T) { + for glob, match := range vGlobs { + testVmoduleGlob(glob, match, t) + } +} + +func TestRollover(t *testing.T) { + setFlags() + var err error + defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) + logExitFunc = func(e error) { + err = e + } + defer func(previous uint64) { MaxSize = previous }(MaxSize) + MaxSize = 512 + + Info("x") // Be sure we have a file. + info, ok := logging.file[infoLog].(*syncBuffer) + if !ok { + t.Fatal("info wasn't created") + } + if err != nil { + t.Fatalf("info has initial error: %v", err) + } + fname0 := info.file.Name() + Info(strings.Repeat("x", int(MaxSize))) // force a rollover + if err != nil { + t.Fatalf("info has error after big write: %v", err) + } + + // Make sure the next log file gets a file name with a different + // time stamp. + // + // TODO: determine whether we need to support subsecond log + // rotation. C++ does not appear to handle this case (nor does it + // handle Daylight Savings Time properly). + time.Sleep(1 * time.Second) + + Info("x") // create a new file + if err != nil { + t.Fatalf("error after rotation: %v", err) + } + fname1 := info.file.Name() + if fname0 == fname1 { + t.Errorf("info.f.Name did not change: %v", fname0) + } + if info.nbytes >= MaxSize { + t.Errorf("file size was not reset: %d", info.nbytes) + } +} + +func TestLogBacktraceAt(t *testing.T) { + setFlags() + defer logging.swap(logging.newBuffers()) + // The peculiar style of this code simplifies line counting and maintenance of the + // tracing block below. + var infoLine string + setTraceLocation := func(file string, line int, ok bool, delta int) { + if !ok { + t.Fatal("could not get file:line") + } + _, file = filepath.Split(file) + infoLine = fmt.Sprintf("%s:%d", file, line+delta) + err := logging.traceLocation.Set(infoLine) + if err != nil { + t.Fatal("error setting log_backtrace_at: ", err) + } + } + { + // Start of tracing block. These lines know about each other's relative position. + _, file, line, ok := runtime.Caller(0) + setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. + Info("we want a stack trace here") + } + numAppearances := strings.Count(contents(infoLog), infoLine) + if numAppearances < 2 { + // Need 2 appearances, one in the log header and one in the trace: + // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here + // ... + // github.com/glog/glog_test.go:280 (0x41ba91) + // ... + // We could be more precise but that would require knowing the details + // of the traceback format, which may not be dependable. + t.Fatal("got no trace back; log is ", contents(infoLog)) + } +} + +func BenchmarkHeader(b *testing.B) { + for i := 0; i < b.N; i++ { + buf, _, _ := logging.header(infoLog, 0) + logging.putBuffer(buf) + } +} diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md index 2cc5165042..ab07019811 100644 --- a/vendor/github.com/pkg/errors/README.md +++ b/vendor/github.com/pkg/errors/README.md @@ -1,6 +1,6 @@ # errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) -Package errors implements functions for manipulating errors. +Package errors provides simple error handling primitives. The traditional error handling idiom in Go is roughly akin to ```go diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go index b0da7c5619..254c6dd06a 100644 --- a/vendor/github.com/pkg/errors/errors.go +++ b/vendor/github.com/pkg/errors/errors.go @@ -1,4 +1,4 @@ -// Package errors implements functions for manipulating errors. +// Package errors provides simple error handling primitives. // // The traditional error handling idiom in Go is roughly akin to // @@ -51,7 +51,6 @@ import ( "errors" "fmt" "io" - "os" "runtime" "strings" ) @@ -202,7 +201,7 @@ func Cause(err error) error { return err } -// Print prints the error to Stderr. +// Fprint prints the error to the supplied writer. // If the error implements the Causer interface described in Cause // Print will recurse into the error's cause. // If the error implements the inteface: @@ -212,12 +211,6 @@ func Cause(err error) error { // } // // Print will also print the file and line of the error. -func Print(err error) { - Fprint(os.Stderr, err) -} - -// Fprint prints the error to the supplied writer. -// The format of the output is the same as Print. // If err is nil, nothing is printed. func Fprint(w io.Writer, err error) { type location interface { diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bexport.go b/vendor/golang.org/x/tools/go/gcimporter15/bexport.go index 1ceae1377d..9ff0d771b9 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/bexport.go +++ b/vendor/golang.org/x/tools/go/gcimporter15/bexport.go @@ -42,6 +42,17 @@ const trace = false // default: false const exportVersion = "v0" +// trackAllTypes enables cycle tracking for all types, not just named +// types. The existing compiler invariants assume that unnamed types +// that are not completely set up are not used, or else there are spurious +// errors. +// If disabled, only named types are tracked, possibly leading to slightly +// less efficient encoding in rare cases. It also prevents the export of +// some corner-case type declarations (but those are not handled correctly +// with with the textual export format either). +// TODO(gri) enable and remove once issues caused by it are fixed +const trackAllTypes = false + type exporter struct { fset *token.FileSet out bytes.Buffer @@ -79,6 +90,12 @@ func BExportData(fset *token.FileSet, pkg *types.Package) []byte { } p.rawByte(format) + format = 'n' // track named types only + if trackAllTypes { + format = 'a' + } + p.rawByte(format) + // posInfo exported or not? p.bool(p.posInfoFormat) @@ -283,15 +300,21 @@ func (p *exporter) typ(t types.Type) { } // otherwise, remember the type, write the type tag (< 0) and type data - index := len(p.typIndex) - if trace { - p.tracef("T%d = {>\n", index) - defer p.tracef("<\n} ") + if trackAllTypes { + if trace { + p.tracef("T%d = {>\n", len(p.typIndex)) + defer p.tracef("<\n} ") + } + p.typIndex[t] = len(p.typIndex) } - p.typIndex[t] = index switch t := t.(type) { case *types.Named: + if !trackAllTypes { + // if we don't track all types, track named types now + p.typIndex[t] = len(p.typIndex) + } + p.tag(namedTag) p.pos(t.Obj()) p.qualifiedName(t.Obj()) diff --git a/vendor/golang.org/x/tools/go/gcimporter15/bimport.go b/vendor/golang.org/x/tools/go/gcimporter15/bimport.go index e6b4863ea4..f3fe519ed1 100644 --- a/vendor/golang.org/x/tools/go/gcimporter15/bimport.go +++ b/vendor/golang.org/x/tools/go/gcimporter15/bimport.go @@ -28,9 +28,10 @@ type importer struct { buf []byte // for reading strings // object lists - strList []string // in order of appearance - pkgList []*types.Package // in order of appearance - typList []types.Type // in order of appearance + strList []string // in order of appearance + pkgList []*types.Package // in order of appearance + typList []types.Type // in order of appearance + trackAllTypes bool // position encoding posInfoFormat bool @@ -68,6 +69,8 @@ func BImportData(fset *token.FileSet, imports map[string]*types.Package, data [] return p.read, nil, fmt.Errorf("invalid encoding format in export data: got %q; want 'c' or 'd'", format) } + p.trackAllTypes = p.rawByte() == 'a' + p.posInfoFormat = p.int() != 0 // --- generic export data --- @@ -102,7 +105,12 @@ func BImportData(fset *token.FileSet, imports map[string]*types.Package, data [] // complete interfaces for _, typ := range p.typList { - if it, ok := typ.(*types.Interface); ok { + // If we only record named types (!p.trackAllTypes), + // we must check the underlying types here. If we + // track all types, the Underlying() method call is + // not needed. + // TODO(gri) Remove if p.trackAllTypes is gone. + if it, ok := typ.Underlying().(*types.Interface); ok { it.Complete() } } @@ -344,7 +352,9 @@ func (p *importer) typ(parent *types.Package) types.Type { case arrayTag: t := new(types.Array) - p.record(t) + if p.trackAllTypes { + p.record(t) + } n := p.int64() *t = *types.NewArray(p.typ(parent), n) @@ -352,35 +362,45 @@ func (p *importer) typ(parent *types.Package) types.Type { case sliceTag: t := new(types.Slice) - p.record(t) + if p.trackAllTypes { + p.record(t) + } *t = *types.NewSlice(p.typ(parent)) return t case dddTag: t := new(dddSlice) - p.record(t) + if p.trackAllTypes { + p.record(t) + } t.elem = p.typ(parent) return t case structTag: t := new(types.Struct) - p.record(t) + if p.trackAllTypes { + p.record(t) + } *t = *types.NewStruct(p.fieldList(parent)) return t case pointerTag: t := new(types.Pointer) - p.record(t) + if p.trackAllTypes { + p.record(t) + } *t = *types.NewPointer(p.typ(parent)) return t case signatureTag: t := new(types.Signature) - p.record(t) + if p.trackAllTypes { + p.record(t) + } params, isddd := p.paramList() result, _ := p.paramList() @@ -393,7 +413,9 @@ func (p *importer) typ(parent *types.Package) types.Type { // such cycle must contain a named type which would have been // first defined earlier. n := len(p.typList) - p.record(nil) + if p.trackAllTypes { + p.record(nil) + } // no embedded interfaces with gc compiler if p.int() != 0 { @@ -401,12 +423,16 @@ func (p *importer) typ(parent *types.Package) types.Type { } t := types.NewInterface(p.methodList(parent), nil) - p.typList[n] = t + if p.trackAllTypes { + p.typList[n] = t + } return t case mapTag: t := new(types.Map) - p.record(t) + if p.trackAllTypes { + p.record(t) + } key := p.typ(parent) val := p.typ(parent) @@ -415,7 +441,9 @@ func (p *importer) typ(parent *types.Package) types.Type { case chanTag: t := new(types.Chan) - p.record(t) + if p.trackAllTypes { + p.record(t) + } var dir types.ChanDir // tag values must match the constants in cmd/compile/internal/gc/go.go diff --git a/vendor/golang.org/x/tools/imports/fix.go b/vendor/golang.org/x/tools/imports/fix.go index 1b0213743c..d13836ce74 100644 --- a/vendor/golang.org/x/tools/imports/fix.go +++ b/vendor/golang.org/x/tools/imports/fix.go @@ -54,6 +54,12 @@ func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []stri // decls are the current package imports. key is base package or renamed package. decls := make(map[string]*ast.ImportSpec) + abs, err := filepath.Abs(filename) + if err != nil { + return nil, err + } + srcDir := path.Dir(abs) + // collect potential uses of packages. var visitor visitFn visitor = visitFn(func(node ast.Node) ast.Visitor { @@ -65,7 +71,7 @@ func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []stri if v.Name != nil { decls[v.Name.Name] = v } else { - local := importPathToName(strings.Trim(v.Path.Value, `\"`)) + local := importPathToName(strings.Trim(v.Path.Value, `\"`), srcDir) decls[local] = v } case *ast.SelectorExpr: @@ -152,17 +158,17 @@ func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []stri var importPathToName = importPathToNameGoPath // importPathToNameBasic assumes the package name is the base of import path. -func importPathToNameBasic(importPath string) (packageName string) { +func importPathToNameBasic(importPath, srcDir string) (packageName string) { return path.Base(importPath) } // importPathToNameGoPath finds out the actual package name, as declared in its .go files. // If there's a problem, it falls back to using importPathToNameBasic. -func importPathToNameGoPath(importPath string) (packageName string) { - if buildPkg, err := build.Import(importPath, "", 0); err == nil { +func importPathToNameGoPath(importPath, srcDir string) (packageName string) { + if buildPkg, err := build.Import(importPath, srcDir, 0); err == nil { return buildPkg.Name } else { - return importPathToNameBasic(importPath) + return importPathToNameBasic(importPath, srcDir) } } @@ -260,7 +266,7 @@ func loadPkg(wg *sync.WaitGroup, root, pkgrelpath string) { } } if hasGo { - shortName := importPathToName(importpath) + shortName := importPathToName(importpath, "") pkgIndex.Lock() pkgIndex.m[shortName] = append(pkgIndex.m[shortName], pkg{ importpath: importpath, diff --git a/vendor/golang.org/x/tools/imports/fix_test.go b/vendor/golang.org/x/tools/imports/fix_test.go index 3506dbd18f..9c89ef6739 100644 --- a/vendor/golang.org/x/tools/imports/fix_test.go +++ b/vendor/golang.org/x/tools/imports/fix_test.go @@ -823,6 +823,60 @@ func TestFixImports(t *testing.T) { } } +// Test for correctly identifying the name of a vendored package when it +// differs from its directory name. In this test, the import line +// "mypkg.com/mypkg.v1" would be removed if goimports wasn't able to detect +// that the package name is "mypkg". +func TestFixImportsVendorPackage(t *testing.T) { + // Skip this test on go versions with no vendor support. + if _, err := os.Stat(filepath.Join(runtime.GOROOT(), "src/vendor")); err != nil { + t.Skip(err) + } + + newGoPath, err := ioutil.TempDir("", "vendortest") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(newGoPath) + + vendoredPath := newGoPath + "/src/mypkg.com/outpkg/vendor/mypkg.com/mypkg.v1" + if err := os.MkdirAll(vendoredPath, 0755); err != nil { + t.Fatal(err) + } + + pkgIndexOnce = &sync.Once{} + oldGOPATH := build.Default.GOPATH + build.Default.GOPATH = newGoPath + defer func() { + build.Default.GOPATH = oldGOPATH + }() + + if err := ioutil.WriteFile(vendoredPath+"/f.go", []byte("package mypkg\nvar Foo = 123\n"), 0666); err != nil { + t.Fatal(err) + } + + input := `package p + +import ( + "fmt" + + "mypkg.com/mypkg.v1" +) + +var ( + _ = fmt.Print + _ = mypkg.Foo +) +` + buf, err := Process(newGoPath+"/src/mypkg.com/outpkg/toformat.go", []byte(input), &Options{}) + if err != nil { + t.Fatal(err) + } + if got := string(buf); got != input { + t.Fatalf("results differ\nGOT:\n%s\nWANT:\n%s\n", got, input) + } +} + func TestFindImportGoPath(t *testing.T) { goroot, err := ioutil.TempDir("", "goimports-") if err != nil { From 9333034606b3b5680f7f188495ae8ffd7001ea20 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Sat, 14 May 2016 09:57:50 -0700 Subject: [PATCH 8/9] Integrate github.com/golang/glog --- cmd/run.go | 40 ++++++++++++++++++++++++++++++++++++++++ runtime/runtime.go | 3 +++ 2 files changed, 43 insertions(+) diff --git a/cmd/run.go b/cmd/run.go index 00fd52addd..e9571ad7c0 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -5,12 +5,16 @@ package cmd import ( + "flag" "os" "path" "path/filepath" + "reflect" + "strings" "github.com/open-policy-agent/opa/runtime" "github.com/spf13/cobra" + "github.com/spf13/pflag" ) // default filename for the interactive shell's history @@ -70,6 +74,9 @@ In addition, API calls to delete policies will remove the definition file. runCommand.Flags().StringVarP(¶ms.PolicyDir, "policy-dir", "p", "", "set directory to store policy definitions") runCommand.Flags().StringVarP(¶ms.Addr, "addr", "a", defaultAddr, "set listening address of the server") + wrapFlags(runCommand.Flags()) + flag.Parse() + usageTemplate := `Usage: {{.UseLine}} [flags] [files] @@ -97,3 +104,36 @@ func policyDir() string { } return filepath.Join(cwd, defaultPolicyDir) } + +type flagWrapper struct { + inner flag.Value + typ string +} + +func (f *flagWrapper) String() string { + return f.inner.String() +} + +func (f *flagWrapper) Set(s string) error { + return f.inner.Set(s) +} + +func (f *flagWrapper) Type() string { + return f.typ +} + +func wrapFlag(v flag.Value) pflag.Value { + if pf, ok := v.(pflag.Value); ok { + return pf + } + return &flagWrapper{ + inner: v, + typ: strings.TrimSuffix(reflect.TypeOf(v).Elem().Name(), "Value"), + } +} + +func wrapFlags(flags *pflag.FlagSet) { + flag.CommandLine.VisitAll(func(flg *flag.Flag) { + flags.Var(wrapFlag(flg.Value), flg.Name, flg.Usage) + }) +} diff --git a/runtime/runtime.go b/runtime/runtime.go index b976297941..dd4f151d5b 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -11,6 +11,7 @@ import ( "os" "path/filepath" + "github.com/golang/glog" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/storage" "github.com/pkg/errors" @@ -104,6 +105,8 @@ func (rt *Runtime) Start(params *Params) { } func (rt *Runtime) startServer(params *Params) { + glog.Warning("First line of log stream.") + glog.V(2).Infof("Server listening address: %v.", params.Addr) persist := len(params.PolicyDir) > 0 server := NewServer(rt, params.Addr, persist) server.Loop() From 12e299fdf241ba3d365f59d98aa448c1e26d9bd7 Mon Sep 17 00:00:00 2001 From: Torin Sandall Date: Sat, 14 May 2016 10:44:02 -0700 Subject: [PATCH 9/9] Add basic access logs Wrap the router so to capture response latency and implement an interceptor that captures status codes and number of bytes written. Log the information once the inner route completes. --- runtime/logging.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++ runtime/server.go | 3 +- 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 runtime/logging.go diff --git a/runtime/logging.go b/runtime/logging.go new file mode 100644 index 0000000000..db996e0ba4 --- /dev/null +++ b/runtime/logging.go @@ -0,0 +1,69 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package runtime + +import ( + "net/http" + "time" + + "github.com/golang/glog" +) + +// LoggingHandler returns an http.Handler that will print log messages to glog +// containing the request information as well as response status and latency. +type LoggingHandler struct { + inner http.Handler +} + +// NewLoggingHandler returns a new http.Handler. +func NewLoggingHandler(inner http.Handler) http.Handler { + return &LoggingHandler{inner} +} + +func (h *LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + recorder := newRecorder(w) + t0 := time.Now() + h.inner.ServeHTTP(recorder, r) + if glog.V(2) { + dt := time.Since(t0) + statusCode := 200 + if recorder.statusCode != 0 { + statusCode = recorder.statusCode + } + glog.Infof("%v %v %v %v %v %vms", + r.RemoteAddr, + r.Method, + r.RequestURI, + statusCode, + recorder.bytesWritten, + float64(dt.Nanoseconds())/1e6) + } +} + +type recorder struct { + inner http.ResponseWriter + bytesWritten int + statusCode int +} + +func newRecorder(w http.ResponseWriter) *recorder { + return &recorder{ + inner: w, + } +} + +func (r *recorder) Header() http.Header { + return r.inner.Header() +} + +func (r *recorder) Write(bs []byte) (int, error) { + r.bytesWritten += len(bs) + return r.inner.Write(bs) +} + +func (r *recorder) WriteHeader(s int) { + r.statusCode = s + r.inner.WriteHeader(s) +} diff --git a/runtime/server.go b/runtime/server.go index 0be393b4c9..fa630fc311 100644 --- a/runtime/server.go +++ b/runtime/server.go @@ -99,7 +99,8 @@ func NewServer(rt *Runtime, addr string, persist bool) *Server { // Loop starts the server. This function does not return. func (s *Server) Loop() { - http.ListenAndServe(s.Addr, s.Router) + wrapped := NewLoggingHandler(s.Router) + http.ListenAndServe(s.Addr, wrapped) } func (s *Server) execQuery(qStr string) (resultSetV1, error) {