You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@trafficcontrol.apache.org by GitBox <gi...@apache.org> on 2018/04/30 23:25:08 UTC

[GitHub] rob05c closed pull request #2188: Add Grove HTTP Caching Proxy

rob05c closed pull request #2188: Add Grove HTTP Caching Proxy
URL: https://github.com/apache/incubator-trafficcontrol/pull/2188
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/LICENSE b/LICENSE
index 670463206..2c37757b5 100644
--- a/LICENSE
+++ b/LICENSE
@@ -426,3 +426,15 @@ For the Pixabay icons:
 @traffic_ops/app/public/images/info.png
 @traffic_ops/app/public/images/graph.png
 ./licenses/CC0
+
+The bytefmt component is used under the Apache 2.0 license:
+@grove/vendor/code.cloudfoundry.org/bytefmt/*
+./grove/vendor/code.cloudfoundry.org/bytefmt/LICENSE
+
+The bytefmt component is used under the MIT license:
+@grove/vendor/github.com/coreos/bbolt/*
+./grove/vendor/github.com/coreos/bbolt/LICENSE
+
+For the siphash component:
+@grove/vendor/github.com/dchest/siphash/*
+./licenses/CC0
diff --git a/grove/README.md b/grove/README.md
new file mode 100644
index 000000000..f8f669e72
--- /dev/null
+++ b/grove/README.md
@@ -0,0 +1,231 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you 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.
+-->
+
+# grove
+
+HTTP caching proxy, implementing RFC 7234
+
+# Building
+
+1. Install and set up a Golang development environment.
+    * See https://golang.org/doc/install
+2. Get the latest necessary golang.org/x packages.
+```bash
+rm -rf $GOPATH/src/golang.org/x
+rm -rf $GOPATH/pkg/*
+
+go get golang.org/x/text
+go get golang.org/x/sys/unix
+go get golang.org/x/net/http2
+go get golang.org/x/net/ipv4
+go get golang.org/x/net/ipv6
+```
+  * golang.org/x must be updated when the Go compiler is, so we treat it as part of the compiler, rather than vendoring it like other dependencies, to avoid breaking updating to newer compilers than we internally work with. If you know what you're doing, feel free to skip this step, or omit `rm` of old `go get` source and packages.
+3. Clone this repository into your GOPATH.
+```bash
+mkdir -p $GOPATH/src/github.com/apache/incubator-trafficcontrol
+cd $GOPATH/src/github.com/apache/incubator-trafficcontrol
+git clone https://github.com/apache/incubator-trafficcontrol/grove
+```
+4. Build the application
+```bash
+cd $GOPATH/src/github.com/apache/incubator-trafficcontrol/grove
+go build
+```
+6. Install and configure an RPM development environment
+   * See https://wiki.centos.org/HowTos/SetupRpmBuildEnvironment
+7. Build the RPM
+```bash
+./build/build_rpm.sh
+```
+
+# Configuration
+
+A config file must be passed with the `-cfg` flag on startup. The RPM uses a config file at `/etc/grove/grove.cfg`.
+
+The config file is JSON of the following format:
+
+```json
+{ "rfc_compliant": false,
+  "port": 8080,
+  "cache_size_bytes": 50000,
+  "remap_rules_file": "./remap.json",
+```
+
+The config file has the following fields:
+
+| Field | Description |
+| --- | --- |
+| `rfc_compliant` | Whether to strictly adhere to RFC 7234. If false, client requests which can harm a parent, such as `no-cache` are ignored. |
+| `port` | The HTTP port to serve on. |
+| `https_port` | The HTTPS port to serve on. |
+| `cache_size_bytes` | The maximum size of the memory cache, in bytes. This is a soft maximum, and the cache may temporarily exceed this size until older values can be purged. The cache uses a Least Recently Used algorithm, purging the oldest requested object when a request for an uncached object is received with a full cache. Also note the cache size calculation does not currently count headers. |
+| `remap_rules_file` | The file with remap rules. See [Remap Rules](#remap-rules). |
+| `concurrent_rule_requests` | The maximum number of simultaneous requests which will be issued to a parent for any rule. |
+| `cert_file` | The global HTTPS certificate file to use, for HTTPS remap rules without certificates specified. |
+| `key_file` | The global HTTPS certificate key file to use, for HTTPS remap rules without certificates specified. |
+| `interface_name` | The name of the network interface to gather statistics for. This does _not_ affect which addresses are bound for listening, currently the app listens on the given port for all addresses, irrespective of interface. |
+| `connection_close` | Whether to send a `Connection: Close` header with responses. This is primarily designed for debugging and operations use, for example, to help remove clients from a cache in order to take it out of service. |
+| `log_location_error` | The location to log error messages to. May be any file, `stdout`, `stderr`, or `null`. |
+| `log_location_warning` | The location to log warning messages to. May be any file, `stdout`, `stderr`, or `null`. |
+| `log_location_info` | The location to log informational messages to. May be any file, `stdout`, `stderr`, or `null`. |
+| `log_location_debug` | The location to log debug messages to. May be any file, `stdout`, `stderr`, or `null`. |
+| `log_location_event` | The location to log access events to. May be any file, `stdout`, `stderr`, or `null`. |
+| `parent_request_timeout_ms` | The timeout in milliseconds for requests to parents. |
+| `parent_request_keep_alive_ms` | The length of time in milliseconds to keep connections to parents alive, for multiple requests. |
+| `parent_request_max_idle_connections` | The maximum number of idle kept-alive connections to retain per parent. |
+| `parent_request_idle_connection_timeout_ms` | The length of time in milliseconds to keep an idle parent connection alive, before terminating it. |
+| `server_idle_timeout_ms` | The length of time in milliseconds to allow a kept-alive client connection to remain idle, before terminating it. |
+| `server_read_timeout_ms` | The length of time in milliseconds to allow a client to read data, before the connection is terminated. This value should be carefully considered, as too short a timeout will result in terminating legitimate clients with slow connections, while too long a timeout will make the server vulnerable to SlowLoris attacks.  |
+| `server_write_timeout_ms` | The length of time in milliseconds to allow a client to write data, before the connection is terminated. This value should be carefully considered, as too short a timeout will result in terminating legitimate clients with slow connections, while too long a timeout will make the server vulnerable to SlowLoris attacks.|
+| `cache_files` | Groups of cache files to use for disk caching. See [Disk Cache](#disk-cache) |
+| `file_mem_bytes` | The size in bytes of the memory cache to use for each group of cache files. Note this size is used for each group, and thus the total memory used is `file_mem_bytes*len(cache_files)+cache_size_bytes`.  See [Disk Cache](#disk-cache) |
+
+# Remap Rules
+
+The remap rules file is specified in the [config file](#configuration).
+
+Note there exists a tool for generating remap rules from [Traffic Control](https://github.com/apache/incubator-trafficcontrol), available [here](https://github.com/apache/incubator-trafficcontrol/grove/tree/master/grovetccfg).
+
+The remap rules file is JSON of the following form:
+
+```json
+{
+    "parent_selection": "consistent-hash",
+    "retry_codes": [ 501, 404 ],
+    "retry_num": null,
+    "rules": [
+        {
+            "allow": [ "::1/128", "0.0.0.0/0" ],
+            "certificate-file": "",
+            "certificate-key-file": "",
+            "concurrent_rule_requests": 0,
+            "connection-close": false,
+            "deny": [ "::1/128", "0.0.0.0/0" ],
+            "from": "http://foo.example.net",
+            "name": "foo.example.com.http.http",
+            "parent_selection": "consistent-hash",
+            "query-string": { "cache": true, "remap": true },
+            "retry_codes": [ 404, 500 ],
+            "retry_num": 5,
+            "cache_name": "disk",
+            "timeout_ms": 5000,
+            "to": [
+                {
+                    "parent_selection": "consistent-hash",
+                    "proxy_url": "http://proxy.example.net:80",
+                    "retry_codes": [ 500, 404 ],
+                    "retry_num": 5,
+                    "timeout_ms": 5000,
+                    "url": "http://bar.example.net",
+                    "weight": 1
+                }
+            ]
+        }
+    ],
+    "timeout_ms": 5000
+}
+```
+
+Rule configuration may be specified at the global, rule, or `to` level, and the most specific field applies. Remap rules have the following configuration fields:
+
+| Field | Description |
+| --- | --- |
+| `retry_num` | The number of times to retry a parent request. |
+| `cache_name` | The name of the cache to use, specified in the global config. Defaults to the memory cache. |
+| `retry_codes` | The HTTP codes which will be considered failures and cause a failure and cause a retry on the next parent. If `retry_num` tries are exceeded, the final failure response will be cached and returned to the client. |
+| `timeout_ms` | The request timeout in milliseconds for the given parent. |
+| `parent_selection` | The parent selection algorithm. Currently, only `consistent-hash` is supported. |
+| `concurrent_rule_requests` | The maximum number of concurrent requests to make to the parent, for this rule. |
+| `allow` | An array of CIDR networks to allow access. This may include both IPv4 and IPv6 networks. Note single IPs must be in CIDR format, e.g. `192.0.2.1/32`. |
+| `deny` | An array of CIDR networks to deny access to. This may include both IPv4 and IPv6 networks. Note single IPs must be in CIDR format, e.g. `192.0.2.1/32`. |
+
+The global object must also include a `rules` key, with an array of rule objects. Each remap rule has the following fields:
+
+| Field | Description |
+| --- | --- |
+| `name` | The internal name for the given rule. This is not used in request mapping, and may be any unique string. |
+| `from` | The request to remap, including the scheme and fully qualified domain name. This may also optionally include URL path parts. |
+| `certificate-file` | The file path for the certificate for this HTTPS request. This field is not used for HTTP requests. |
+| `certificate-key-file` | The file path for the certificate key for this HTTPS request. This field is not used for HTTP requests. |
+| `connection-close` | Whether to add a `Connection: Close` header to client responses for this rule. This is designed for maintenance, operations, or debugging. |
+| `query-string` | A JSON object with the boolean keys `remap` and `cache`. The `remap` key indicates whether to append request query strings to the parent request. The `cache` key incidates whether to cache requests with different query strings separately. |
+| `to` | The array of parents for the given rule. |
+
+The objects in the `to` array of parents have the following fields:
+
+| Field | Description |
+| --- | --- |
+| `url` | The parent URL to remap to, including the scheme and fully qualified domain name. This may also optionally include URL path parts. |
+| `weight` | The weight of this parent in the parent selection algorithm. |
+| `proxy_url` | The proxy URL, if this parent is being used as a forward proxy. Must include the scheme, fully qualified domain name, and port. If this rule is omitted, the parent will be requested directly with the `url` as a reverse proxy. |
+
+# Remap Rules and Nonstandard Ports
+In the remap rules file, the `from` is mapped verbatim to the `to`, and `from` is the `Host` header, Grove doesn't care anything about what DNS thinks the server is.
+
+This is especially confusing when Grove is running on a nonstandard port, because clients (like `curl`) will automatically append the port. For example, if Grove is serving at `http://foo.example:8080`, then `curl http://foo.example:8080/bar` will automatically send a `Host` header of `foo.example:8080`. This means, to work with clients automatically sending the port, the `from` remap must be `http://foo.example:8080`, not `http://foo.example`. Otherwise, because the mapping is done verbatim, it will match only the part before the port, and include the port in the remap.
+
+For example, if a remap rule exists from `http://foo.example` and to `http://bar.example:1234`, and Grove is serving on `:8080`, a request to `curl http://foo.example:8080/baz` will automatically send `Host: foo.example:8080`, and Grove will find a remap match and replace `http://foo.example` with `http://bar.example`, resulting in a malformed parent of `http://bar.example:1234:8080/baz`. Which is almost certainly not what you want.
+
+Therefore, for the literal Host header remapping Grove does, when Grove is serving on a nonstandard port, including the port in the `from` is almost always the right solution. Alternatively, if clients are known to be sending a `Host` header without the port, even to requests at a nonstandard port, the port must not be included in order for the remap rule to match.
+
+# Disk Cache
+
+By default, all remap rules use a shared memory cache, of the size specified in the global config `cache_size_bytes` key. However, it is also possible to use disk caching.
+
+Disk caching uses files, organized into groups. They are specified in the global config with the key `cache_files`, of the form:
+
+```json
+"cache_files": {
+    "my-disk-cache": [
+        {
+          "path": "/mnt/sdb/diskcachefile0.db",
+          "size_bytes": 100000000000
+        },
+        {
+          "path": "/mnt/sdc/diskcachefile1.db",
+          "size_bytes": 100000000000
+        }
+    ],
+    "my-disk-cache-two": [
+        {
+          "path": "/etc/grove/singlefilecache.db",
+          "size_bytes": 1000000000
+        }
+    ]
+},
+```
+
+Then, to specify that a remap rule uses the disk cache, add `"cache_name": "my-disk-cache",` to that remap rule's object in the remap rules file.
+
+Note the `size_bytes` is a soft maximum, as with the memory cache, which may be exceeded in order to perform better than a hard maximum.
+
+Each cache of disk files also has a memory cache in front of it, for performance. The size of this memory cache is determined by the global config `file_mem_bytes` setting.
+
+Groups of files are used primarily to allow a cache to distribute objects across multiple physical devices. Each request object will be consistent-hashed to a file.
+You can, of course, use a single file.
+
+Each file is a key-value database, which internally uses a B+tree (see https://github.com/coreos/bbolt). The database is optimized for read over write, and access is frequently random so SSDs should outperform HDDs.
+
+# Running
+
+The application may be run manually via `./grove -cfg grove.cfg`, or if installed via the RPM, as a service via `service grove start` or `systemctl start grove`.
+
+If there are errors, they will be logged to the error location in the config file (`/etc/grove/grove.cfg` for the service), or if the errors are with the config file itself, to stdout.
+
diff --git a/grove/VERSION b/grove/VERSION
new file mode 100644
index 000000000..49d59571f
--- /dev/null
+++ b/grove/VERSION
@@ -0,0 +1 @@
+0.1
diff --git a/grove/build/build_rpm.sh b/grove/build/build_rpm.sh
new file mode 100755
index 000000000..f6111009f
--- /dev/null
+++ b/grove/build/build_rpm.sh
@@ -0,0 +1,34 @@
+#!/usr/bin/env bash
+
+# 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.
+
+BUILDDIR="$HOME/rpmbuild"
+
+VERSION=`cat ./VERSION`.`git rev-list --all --count`
+
+# prep build environment
+rm -rf $BUILDDIR
+mkdir -p $BUILDDIR/{BUILD,RPMS,SOURCES}
+echo "$BUILDDIR" > ~/.rpmmacros
+
+# build
+go build -v -ldflags "-X main.Version=$VERSION"
+
+# tar
+tar -cvzf $BUILDDIR/SOURCES/grove-${VERSION}.tgz grove conf/grove.cfg build/grove.init
+
+# build RPM
+rpmbuild --define "version ${VERSION}" -ba build/grove.spec
+
+# copy build RPM to .
+cp $BUILDDIR/RPMS/x86_64/grove-${VERSION}-1.x86_64.rpm .
diff --git a/grove/build/grove.init b/grove/build/grove.init
new file mode 100755
index 000000000..adb3b80e4
--- /dev/null
+++ b/grove/build/grove.init
@@ -0,0 +1,119 @@
+#!/bin/bash
+
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+# Startup script for grove
+#
+#
+# chkconfig: 345 99 10
+# description: grove control script
+# processname: grove
+
+### BEGIN INIT INFO
+# Provides: grove
+# Required-Start: $network $local_fs $syslog
+# Required-Stop: $network $local_fs $syslog
+# Default-Start: 3 4 5
+# Default-Stop: 0 1 2 6
+# Short-Description: start and stop Grove
+# Description: Controls all grove processes at once.
+### END INIT INFO
+
+# Source function library.
+. /etc/init.d/functions
+
+# Source networking configuration.
+. /etc/sysconfig/network
+
+name=grove
+basepath=/usr/sbin
+runpath=/var/run
+prog=$basepath/$name
+lockfile=$runpath/$name
+
+options="-cfg /etc/${name}/grove.cfg"
+
+start() {
+        [ "$NETWORKING" = "no" ] && exit 1
+        [ -x $prog ] || exit 5
+
+        #Set file limits
+        # Max open files
+        OPEN_FILE_LIMIT=65536
+        ulimit -n $OPEN_FILE_LIMIT
+        if [ $? -ne 0 ]; then
+            echo -n "Failed to set open file limit to $OPEN_FILE_LIMIT"
+            exit 1
+        fi
+
+        # Start daemons.
+        echo -n $"Starting $name: "
+        daemon nohup $prog $options < /dev/null > /var/log/${name}/${name}.log 2>&1 &
+        RETVAL=$?
+        echo
+        [ $RETVAL -eq 0 ] && touch $lockfile
+        return $RETVAL
+}
+
+stop() {
+        echo -n $"Shutting down $name: "
+        killproc $prog
+        RETVAL=$?
+        echo
+        [ $RETVAL -eq 0 ] && rm -f $lockfile
+        return $RETVAL
+}
+
+reload() {
+        echo -n $"Reloading $name: "
+        if [ -n "`pidofproc $prog`" ]; then
+                killproc $prog -HUP
+        else
+                failure $"Reloading $name"
+        fi
+        RETVAL=$?
+        echo
+}
+
+case "$1" in
+  start)
+        start
+        ;;
+  stop)
+        stop
+        ;;
+  status)
+        status $prog
+        ;;
+  restart|force-reload)
+        stop
+        start
+        ;;
+  try-restart|condrestart)
+        if status $prog > /dev/null; then
+            stop
+            start
+        fi
+        ;;
+  reload)
+        reload
+        ;;
+  *)
+        echo $"Usage: $0 {start|stop|status|restart|try-restart|reload|force-reload}"
+        exit 2
+esac
diff --git a/grove/build/grove.logrotate b/grove/build/grove.logrotate
new file mode 100644
index 000000000..be57fdc81
--- /dev/null
+++ b/grove/build/grove.logrotate
@@ -0,0 +1,36 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+
+/var/log/grove/grove.log {
+        compress
+        maxage 30
+        missingok
+        nomail
+        size 10M
+        rotate 5
+        copytruncate
+}
+
+/var/log/grove/access.log {
+        compress
+        maxage 30
+        missingok
+        nomail
+        size 10M
+        rotate 5
+        copytruncate
+}
diff --git a/grove/build/grove.spec b/grove/build/grove.spec
new file mode 100644
index 000000000..ec3389d15
--- /dev/null
+++ b/grove/build/grove.spec
@@ -0,0 +1,59 @@
+# 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.
+
+Summary: Grove HTTP Caching Proxy
+Name: grove
+Version: %{version}
+Release: 1
+License: Apache License, Version 2.0
+Group: Base System/System Tools
+Prefix: /usr/sbin/%{name}
+Source: %{_sourcedir}/%{name}-%{version}.tgz
+URL: https://github.com/apache/incubator-trafficcontrol/%{name}
+Distribution: CentOS Linux
+Vendor: Apache Software Foundation
+BuildRoot: %{buildroot}
+
+# %define PACKAGEDIR %{prefix}
+
+%description
+An HTTP Caching Proxy
+
+%prep
+
+%build
+tar -xvzf %{_sourcedir}/%{name}-%{version}.tgz --directory %{_builddir}
+
+%install
+rm -rf %{buildroot}/usr/sbin/%{name}
+mkdir -p %{buildroot}/usr/sbin/
+cp -p %{name} %{buildroot}/usr/sbin/
+
+rm -rf %{buildroot}/etc/%{name}
+mkdir -p -m 777 %{buildroot}/etc/%{name}
+cp -p conf/%{name}.cfg %{buildroot}/etc/%{name}
+
+rm -rf %{buildroot}/var/log/%{name}
+mkdir -p -m 777 %{buildroot}/var/log/%{name}
+
+mkdir -p -m 777 %{buildroot}/etc/init.d/
+cp -p  build/%{name}.init %{buildroot}/etc/init.d/%{name}
+
+%clean
+echo "cleaning"
+rm -r -f %{buildroot}
+
+%files
+/usr/sbin/%{name}
+/var/log/%{name}
+%config(noreplace) /etc/%{name}
+/etc/init.d/%{name}
diff --git a/grove/cache/handler.go b/grove/cache/handler.go
new file mode 100644
index 000000000..a7a7f4a16
--- /dev/null
+++ b/grove/cache/handler.go
@@ -0,0 +1,315 @@
+package cache
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"os"
+	"strconv"
+	"sync/atomic"
+	"time"
+	"unsafe"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cachedata"
+	"github.com/apache/incubator-trafficcontrol/grove/plugin"
+
+	"github.com/apache/incubator-trafficcontrol/grove/remap"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/stat"
+	"github.com/apache/incubator-trafficcontrol/grove/thread"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+type HandlerPointer struct {
+	realHandler *unsafe.Pointer
+}
+
+func NewHandlerPointer(realHandler *Handler) *HandlerPointer {
+	p := (unsafe.Pointer)(realHandler)
+	return &HandlerPointer{realHandler: &p}
+}
+
+func (h *HandlerPointer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	realHandler := (*Handler)(atomic.LoadPointer(h.realHandler))
+	realHandler.ServeHTTP(w, r)
+}
+
+func (h *HandlerPointer) Set(newHandler *Handler) {
+	p := (unsafe.Pointer)(newHandler)
+	atomic.StorePointer(h.realHandler, p)
+}
+
+type Handler struct {
+	remapper        remap.HTTPRequestRemapper
+	getter          thread.Getter
+	ruleThrottlers  map[string]thread.Throttler // doesn't need threadsafe keys, because it's never added to or deleted after creation. TODO fix for hot rule reloading
+	scheme          string
+	port            string
+	hostname        string
+	strictRFC       bool
+	stats           stat.Stats
+	conns           *web.ConnMap
+	connectionClose bool
+	plugins         plugin.Plugins
+	pluginContext   map[string]*interface{}
+	httpConns       *web.ConnMap
+	httpsConns      *web.ConnMap
+	interfaceName   string
+	requestID       uint64 // Atomic - DO NOT access or modify without atomic operations
+	// keyThrottlers     Throttlers
+	// nocacheThrottlers Throttlers
+}
+
+// func (h *cacheHandler) checkoutKeyThrottler(k string) Throttler {
+// 	keyThrottlersM.Lock()
+// 	defer keyThrottlersM.Unlock()
+// 	if t, ok := keyThrottlers[k]; !ok {
+// 		keyThrottlers[k] = NewThrottler
+// 	}
+// 	return keyThrottlers[k]
+// }
+
+// NewHandler returns an http.Handler object, which may be pipelined with other http.Handlers via `http.ListenAndServe`. If you prefer pipelining functions, use `GetHandlerFunc`.
+//
+// This needs rate-limited in 3 ways.
+// 1. ruleLimit - Simultaneous requests to the origin (remap rule) should be configurably limited. For example, "only allow 1000 simultaneous requests to the origin
+// 2. keyLimit - Simultaneous requests, on cache miss, for the same key (Method+Path+Qstring), should be configurably limited. For example, "Only allow 10 simultaneous requests per unique URL on cache miss. Additional requestors must wait until others complete. Once another requestor completes, all waitors for the same URL are signalled to use the cache, or proceed to the third uncacheable limiter"
+// 3. nocacheLimit - If simultaneous requestors exceed the URL limiter, and some request for the same key gets a result which is uncacheable, waitors for the same URL may then proceed at a third configurable limit for uncacheable requests.
+//
+// Note these only apply to cache misses. Cache hits are not limited in any way, the origin is not hit and the cache value is immediately returned to the client.
+//
+// This prevents a large number of uncacheable requests for the same URL from timing out because they're required to proceed serially from the low simultaneous-requests-per-URL limit, while at the same time only hitting the origin with a very low limit for many simultaneous cacheable requests.
+//
+// Example: Origin limit is 10,000, key limit is 1, the uncacheable limit is 1,000.
+// Then, 2,000 requests come in for the same URL, simultaneously. They are all within the Origin limit, so they are all allowed to proceed to the key limiter. Then, the first request is allowed to make an actual request to the origin, while the other 1,999 wait at the key limiter.
+//
+// The connectionClose parameter determines whether to send a `Connection: close` header. This is primarily designed for maintenance, to drain the cache of incoming requestors. This overrides rule-specific `connection-close: false` configuration, under the assumption that draining a cache is a temporary maintenance operation, and if connectionClose is true on the service and false on some rules, those rules' configuration is probably a permament setting whereas the operator probably wants to drain all connections if the global setting is true. If it's necessary to leave connection close false on some rules, set all other rules' connectionClose to true and leave the global connectionClose unset.
+func NewHandler(
+	remapper remap.HTTPRequestRemapper,
+	ruleLimit uint64,
+	stats stat.Stats,
+	scheme string,
+	port string,
+	conns *web.ConnMap,
+	strictRFC bool,
+	connectionClose bool,
+	plugins plugin.Plugins,
+	pluginContext map[string]*interface{},
+	httpConns *web.ConnMap,
+	httpsConns *web.ConnMap,
+	interfaceName string,
+) *Handler {
+	hostname, err := os.Hostname()
+	if err != nil {
+		log.Errorf("getting  hostname: %v\n", err)
+	}
+
+	return &Handler{
+		remapper:        remapper,
+		getter:          thread.NewGetter(),
+		ruleThrottlers:  makeRuleThrottlers(remapper, ruleLimit),
+		strictRFC:       strictRFC,
+		scheme:          scheme,
+		port:            port,
+		hostname:        hostname,
+		stats:           stats,
+		conns:           conns,
+		connectionClose: connectionClose,
+		plugins:         plugins,
+		pluginContext:   pluginContext,
+		httpConns:       httpConns,
+		httpsConns:      httpsConns,
+		interfaceName:   interfaceName,
+		// keyThrottlers:     NewThrottlers(keyLimit),
+		// nocacheThrottlers: NewThrottlers(nocacheLimit),
+	}
+}
+
+func makeRuleThrottlers(remapper remap.HTTPRequestRemapper, limit uint64) map[string]thread.Throttler {
+	remapRules := remapper.Rules()
+	ruleThrottlers := make(map[string]thread.Throttler, len(remapRules))
+	for _, rule := range remapRules {
+		ruleLimit := uint64(rule.ConcurrentRuleRequests)
+		if rule.ConcurrentRuleRequests == 0 {
+			ruleLimit = limit
+		}
+		ruleThrottlers[rule.Name] = thread.NewThrottler(ruleLimit)
+	}
+	return ruleThrottlers
+}
+
+func copyPluginContext(context map[string]*interface{}) map[string]*interface{} {
+	new := make(map[string]*interface{}, len(context))
+	for k, v := range context {
+		newV := *v
+		new[k] = &newV
+	}
+	return new
+}
+
+func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	reqTime := time.Now()
+	reqID := atomic.AddUint64(&h.requestID, 1)
+	pluginContext := copyPluginContext(h.pluginContext) // must give each request a copy, because they can modify in parallel
+	srvrData := cachedata.SrvrData{h.hostname, h.port, h.scheme}
+	onReqData := plugin.OnRequestData{W: w, R: r, Stats: h.stats, StatRules: h.remapper.StatRules(), HTTPConns: h.httpConns, HTTPSConns: h.httpsConns, InterfaceName: h.interfaceName, SrvrData: srvrData, RequestID: reqID}
+	stop := h.plugins.OnRequest(h.remapper.PluginCfg(), pluginContext, onReqData)
+	if stop {
+		return
+	}
+
+	conn := (*web.InterceptConn)(nil)
+	if realConn, ok := h.conns.Get(r.RemoteAddr); !ok {
+		log.Errorf("RemoteAddr '%v' not in Conns (reqid %v)\n", r.RemoteAddr, reqID)
+	} else {
+		if conn, ok = realConn.(*web.InterceptConn); !ok {
+			log.Errorf("Could not get Conn info: Conn is not an InterceptConn: %T (reqid %v)\n", realConn, reqID)
+		}
+	}
+
+	remappingProducer, err := h.remapper.RemappingProducer(r, h.scheme)
+
+	if err == nil { // if we failed to get a remapping, there's no DSCP to set.
+		if err := conn.SetDSCP(remappingProducer.DSCP()); err != nil {
+			log.Errorln(time.Now().Format(time.RFC3339Nano) + " " + r.RemoteAddr + " " + r.Method + " " + r.RequestURI + ": could not set DSCP: " + err.Error() + " (reqid " + strconv.FormatUint(reqID, 10) + ")")
+		}
+	}
+
+	reqHeader := web.CopyHeader(r.Header) // copy request header, because it's not guaranteed valid after actually issuing the request
+	clientIP, _ := web.GetClientIPPort(r)
+
+	toFQDN := ""
+	pluginCfg := map[string]interface{}{}
+	if remappingProducer != nil {
+		toFQDN = remappingProducer.FirstFQDN()
+		pluginCfg = remappingProducer.PluginCfg()
+	}
+
+	reqData := cachedata.ReqData{r, conn, clientIP, reqTime, toFQDN}
+	responder := NewResponder(w, pluginCfg, pluginContext, srvrData, reqData, h.plugins, h.stats, reqID)
+
+	if err != nil {
+		switch err {
+		case remap.ErrRuleNotFound:
+			log.Debugf("rule not found for %v (reqid %v)\n", r.RequestURI, reqID)
+			*responder.ResponseCode = http.StatusNotFound
+		case remap.ErrIPNotAllowed:
+			log.Debugf("IP %v not allowed (reqid %v)\n", r.RemoteAddr, reqID)
+			*responder.ResponseCode = http.StatusForbidden
+		default:
+			log.Debugf("request error: %v (reqid %v)\n", err, reqID)
+		}
+		responder.OriginConnectFailed = true
+		responder.Do()
+		return
+	}
+
+	reqCacheControl := web.ParseCacheControl(reqHeader)
+	log.Debugf("Serve got Cache-Control %+v (reqid %v)\n", reqCacheControl, reqID)
+
+	connectionClose := h.connectionClose || remappingProducer.ConnectionClose()
+	cacheKey := remappingProducer.CacheKey()
+	retrier := NewRetrier(h, reqHeader, reqTime, reqCacheControl, remappingProducer, reqID)
+
+	cache := remappingProducer.Cache()
+
+	var reqHost *string
+	cacheObj, ok := cache.Get(cacheKey)
+	if !ok {
+		log.Debugf("cache.Handler.ServeHTTP: '%v' not in cache (reqid %v)\n", cacheKey, reqID)
+		beforeParentRequestData := plugin.BeforeParentRequestData{Req: r, RemapRule: remappingProducer.Name()}
+		h.plugins.OnBeforeParentRequest(remappingProducer.PluginCfg(), pluginContext, beforeParentRequestData)
+		cacheObj, reqHost, err = retrier.Get(r, nil)
+		if err != nil {
+			log.Errorf("retrying get error (in uncached): %v (reqid %v)\n", err, reqID)
+			responder.OriginConnectFailed = true
+			responder.ProxyStr = cacheObj.ProxyURL
+			if reqHost != nil {
+				responder.ToFQDN = *reqHost
+			}
+			responder.Do()
+			return
+		}
+
+		responder.OriginCode = cacheObj.OriginCode
+		// create new pointers, so plugins don't modify the cacheObj
+		codePtr, hdrsPtr, bodyPtr := cacheObj.Code, cacheObj.RespHeaders, cacheObj.Body
+		responder.SetResponse(&codePtr, &hdrsPtr, &bodyPtr, connectionClose)
+		responder.OriginReqSuccess = true
+		responder.ProxyStr = cacheObj.ProxyURL
+		if reqHost != nil {
+			responder.ToFQDN = *reqHost
+		}
+		beforeRespData := plugin.BeforeRespondData{Req: r, CacheObj: cacheObj, Code: &codePtr, Hdr: &hdrsPtr, Body: &bodyPtr, RemapRule: remappingProducer.Name()}
+		h.plugins.OnBeforeRespond(remappingProducer.PluginCfg(), pluginContext, beforeRespData)
+		responder.Do()
+		return
+	}
+
+	reqHeaders := r.Header
+	canReuseStored := remap.CanReuseStored(reqHeaders, cacheObj.RespHeaders, reqCacheControl, cacheObj.RespCacheControl, cacheObj.ReqHeaders, cacheObj.ReqRespTime, cacheObj.RespRespTime, h.strictRFC)
+
+	if canReuseStored != remapdata.ReuseCan { // run the BeforeParentRequest hook for revalidations / ReuseCannot
+		beforeParentRequestData := plugin.BeforeParentRequestData{Req: r, RemapRule: remappingProducer.Name()}
+		h.plugins.OnBeforeParentRequest(remappingProducer.PluginCfg(), pluginContext, beforeParentRequestData)
+	}
+
+	switch canReuseStored {
+	case remapdata.ReuseCan:
+		log.Debugf("cache.Handler.ServeHTTP: '%v' cache hit! (reqid %v)\n", cacheKey, reqID)
+	case remapdata.ReuseCannot:
+		log.Debugf("cache.Handler.ServeHTTP: '%v' can't reuse (reqid %v)\n", cacheKey, reqID)
+		cacheObj, reqHost, err = retrier.Get(r, nil)
+		if err != nil {
+			log.Errorf("retrying get error (in reuse-cannot): %v (reqid %v)\n", err, reqID)
+			responder.Do()
+			return
+		}
+	case remapdata.ReuseMustRevalidate:
+		log.Debugf("cache.Handler.ServeHTTP: '%v' must revalidate (reqid %v)\n", cacheKey, reqID)
+		cacheObj, reqHost, err = retrier.Get(r, cacheObj)
+		if err != nil {
+			log.Errorf("retrying get error: %v (reqid %v)\n", err, reqID)
+			responder.Do()
+			return
+		}
+	case remapdata.ReuseMustRevalidateCanStale:
+		log.Debugf("cache.Handler.ServeHTTP: '%v' must revalidate (but allowed stale) (reqid %v)\n", cacheKey, reqID)
+		oldCacheObj := cacheObj
+		cacheObj, reqHost, err = retrier.Get(r, cacheObj)
+		if err != nil {
+			log.Errorf("retrying get error - serving stale as allowed: %v (reqid %v)\n", err, reqID)
+			cacheObj = oldCacheObj
+		}
+	}
+	log.Debugf("cache.Handler.ServeHTTP: '%v' responding with %v (reqid %v)\n", cacheKey, cacheObj.Code, reqID)
+
+	// create new pointers, so plugins don't modify the cacheObj
+	codePtr, hdrsPtr, bodyPtr := cacheObj.Code, cacheObj.RespHeaders, cacheObj.Body
+	responder.SetResponse(&codePtr, &hdrsPtr, &bodyPtr, connectionClose)
+	responder.OriginReqSuccess = true
+	responder.Reuse = canReuseStored
+	responder.OriginCode = cacheObj.OriginCode
+	responder.OriginBytes = cacheObj.Size
+	responder.ProxyStr = cacheObj.ProxyURL
+	if reqHost != nil {
+		responder.ToFQDN = *reqHost
+	}
+	beforeRespData := plugin.BeforeRespondData{Req: r, CacheObj: cacheObj, Code: &codePtr, Hdr: &hdrsPtr, Body: &bodyPtr, RemapRule: remappingProducer.Name()}
+	h.plugins.OnBeforeRespond(remappingProducer.PluginCfg(), pluginContext, beforeRespData)
+	responder.Do()
+}
diff --git a/grove/cache/responder.go b/grove/cache/responder.go
new file mode 100644
index 000000000..a211f0ef2
--- /dev/null
+++ b/grove/cache/responder.go
@@ -0,0 +1,112 @@
+package cache
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cachedata"
+	"github.com/apache/incubator-trafficcontrol/grove/plugin"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/stat"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+// Responder is an object encapsulating the cache's response to the client. It holds all the data necessary to respond, log the response, and add the stats.
+type Responder struct {
+	W             http.ResponseWriter
+	RequestID     uint64
+	PluginCfg     map[string]interface{}
+	Plugins       plugin.Plugins
+	PluginContext map[string]*interface{}
+	Stats         stat.Stats
+	F             RespondFunc
+	ResponseCode  *int
+	cachedata.ParentRespData
+	cachedata.SrvrData
+	cachedata.ReqData
+}
+
+func DefaultParentRespData() cachedata.ParentRespData {
+	return cachedata.ParentRespData{
+		Reuse:               remapdata.ReuseCannot,
+		OriginCode:          0,
+		OriginReqSuccess:    false,
+		OriginConnectFailed: false,
+		OriginBytes:         0,
+		ProxyStr:            "-",
+	}
+}
+
+func DefaultRespCode() *int {
+	c := http.StatusBadRequest
+	return &c
+}
+
+type RespondFunc func() (uint64, error)
+
+// NewResponder creates a Responder, which defaults to a generic error response.
+func NewResponder(w http.ResponseWriter, pluginCfg map[string]interface{}, pluginContext map[string]*interface{}, srvrData cachedata.SrvrData, reqData cachedata.ReqData, plugins plugin.Plugins, stats stat.Stats, reqID uint64) *Responder {
+	responder := &Responder{
+		W:              w,
+		RequestID:      reqID,
+		PluginCfg:      pluginCfg,
+		Plugins:        plugins,
+		PluginContext:  pluginContext,
+		Stats:          stats,
+		ResponseCode:   DefaultRespCode(),
+		ParentRespData: DefaultParentRespData(),
+		SrvrData:       srvrData,
+		ReqData:        reqData,
+	}
+	responder.F = func() (uint64, error) { return web.ServeErr(w, *responder.ResponseCode) }
+	return responder
+}
+
+// SetResponse is a helper which sets the RespondFunc of r to `web.Respond` with the given code, headers, body, and connectionClose. Note it takes a pointer to the headers and body, which may be modified after calling this but before the Do() sends the response.
+func (r *Responder) SetResponse(code *int, hdrs *http.Header, body *[]byte, connectionClose bool) {
+	r.ResponseCode = code
+	r.F = func() (uint64, error) {
+		if r.Req.Method == http.MethodHead {
+			*body = nil
+		}
+		return web.Respond(r.W, *code, *hdrs, *body, connectionClose)
+	}
+}
+
+// Do responds to the client, according to the data in r, with the given code, headers, and body. It additionally writes to the event log, and adds statistics about this request. This should always be called for the final response to a client, in order to properly log, stat, and other final operations.
+// For cache misses, reuse should be ReuseCannot.
+// For parent connect failures, originCode should be 0.
+func (r *Responder) Do() {
+	// TODO move plugins.BeforeRespond here? How do we distinguish between success, and know to set headers? r.OriginReqSuccess?
+	bytesSent, err := r.F()
+	if err != nil {
+		log.Errorln(time.Now().Format(time.RFC3339Nano) + " " + r.Req.RemoteAddr + " " + r.Req.Method + " " + r.Req.RequestURI + ": responding: " + err.Error())
+	}
+	web.TryFlush(r.W) // TODO remove? Let plugins do it, if they need to?
+
+	respSuccess := err != nil
+	respData := cachedata.RespData{*r.ResponseCode, bytesSent, respSuccess, isCacheHit(r.Reuse, r.OriginCode)}
+	arData := plugin.AfterRespondData{W: r.W, Stats: r.Stats, ReqData: r.ReqData, SrvrData: r.SrvrData, ParentRespData: r.ParentRespData, RespData: respData, RequestID: r.RequestID}
+	r.Plugins.OnAfterRespond(r.PluginCfg, r.PluginContext, arData)
+}
+
+func isCacheHit(reuse remapdata.Reuse, originCode int) bool {
+	// TODO move to web? remap?
+	return reuse == remapdata.ReuseCan || ((reuse == remapdata.ReuseMustRevalidate || reuse == remapdata.ReuseMustRevalidateCanStale) && originCode == http.StatusNotModified)
+}
diff --git a/grove/cache/retryinggetter.go b/grove/cache/retryinggetter.go
new file mode 100644
index 000000000..12a0cf817
--- /dev/null
+++ b/grove/cache/retryinggetter.go
@@ -0,0 +1,203 @@
+package cache
+
+/*
+   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.
+*/
+
+import (
+	"errors"
+	"net/http"
+	"net/url"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+	"github.com/apache/incubator-trafficcontrol/grove/remap"
+	"github.com/apache/incubator-trafficcontrol/grove/thread"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+const CodeConnectFailure = http.StatusBadGateway
+
+type Retrier struct {
+	H                 *Handler
+	ReqHdr            http.Header
+	ReqTime           time.Time
+	ReqCacheControl   web.CacheControl
+	RemappingProducer *remap.RemappingProducer
+	ReqID             uint64
+}
+
+func NewRetrier(h *Handler, reqHdr http.Header, reqTime time.Time, reqCacheControl web.CacheControl, remappingProducer *remap.RemappingProducer, reqID uint64) *Retrier {
+	return &Retrier{
+		H:                 h,
+		ReqHdr:            reqHdr,
+		ReqCacheControl:   reqCacheControl,
+		RemappingProducer: remappingProducer,
+		ReqID:             reqID,
+	}
+}
+
+// Get takes the HTTP request and the cached object if there is one, and makes a new request, retrying according to its RemappingProducer. If no cached object exists, pass a nil obj.
+// Along with the cacheobj.CacheObj, a string pointer to the request hostname used to fetch the cacheobj.CacheObj is returned.
+func (r *Retrier) Get(req *http.Request, obj *cacheobj.CacheObj) (*cacheobj.CacheObj, *string, error) {
+	retryGetFunc := func(remapping remap.Remapping, retryFailures bool, obj *cacheobj.CacheObj) *cacheobj.CacheObj {
+		// return true for Revalidate, and issue revalidate requests separately.
+		canReuse := func(cacheObj *cacheobj.CacheObj) bool {
+			return remap.CanReuse(r.ReqHdr, r.ReqCacheControl, cacheObj, r.H.strictRFC, true)
+		}
+		getAndCache := func() *cacheobj.CacheObj {
+			return GetAndCache(remapping.Request, remapping.ProxyURL, remapping.CacheKey, remapping.Name, remapping.Request.Header, r.ReqTime, r.H.strictRFC, remapping.Cache, r.H.ruleThrottlers[remapping.Name], obj, remapping.Timeout, retryFailures, remapping.RetryNum, remapping.RetryCodes, remapping.Transport, r.ReqID)
+		}
+		gotObj, getReqID := r.H.getter.Get(remapping.CacheKey, getAndCache, canReuse, r.ReqID)
+
+		req := remapping.Request
+		log.Debugf("Retrier.Get Y URI %v %v %v remapping.CacheKey %v rule %v parent %v code %v headers %+v len(body) %v getterid %v (reqid %v)\n", req.URL.Scheme, req.URL.Host, req.URL.EscapedPath(), remapping.CacheKey, remapping.Name, remapping.ProxyURL, gotObj.Code, gotObj.RespHeaders, len(gotObj.Body), getReqID, r.ReqID)
+
+		return gotObj
+	}
+
+	return retryingGet(retryGetFunc, req, r.RemappingProducer, obj)
+}
+
+// retryingGet takes a function, and retries failures up to the RemappingProducer RetryNum limit. On failure, it creates a new remapping. The func f should use `remapping` to make its request. If it hits failures up to the limit, it returns the last received cacheobj.CacheObj
+// Along with the cacheobj.CacheObj, a string pointer to the request hostname used to fetch the cacheobj.CacheObj is returned.
+// TODO refactor to not close variables - it's awkward and confusing.
+func retryingGet(getCacheObj func(remapping remap.Remapping, retryFailures bool, obj *cacheobj.CacheObj) *cacheobj.CacheObj, request *http.Request, remappingProducer *remap.RemappingProducer, cachedObj *cacheobj.CacheObj) (*cacheobj.CacheObj, *string, error) {
+	obj := (*cacheobj.CacheObj)(nil)
+	for {
+		remapping, retryAllowed, err := remappingProducer.GetNext(request)
+		if err == remap.ErrNoMoreRetries {
+			if obj == nil {
+				return nil, nil, errors.New("remapping producer allows no requests") // should never happen
+			}
+			return obj, nil, nil
+		} else if err != nil {
+			return nil, nil, err
+		}
+		obj = getCacheObj(remapping, retryAllowed, cachedObj)
+		if !isFailure(obj, remapping.RetryCodes) {
+			return obj, &remapping.Request.URL.Host, nil
+		}
+	}
+}
+
+func isFailure(o *cacheobj.CacheObj, retryCodes map[int]struct{}) bool {
+	_, failureCode := retryCodes[o.Code]
+	return failureCode || o.Code == CodeConnectFailure
+}
+
+const ModifiedSinceHdr = "If-Modified-Since"
+
+// GetAndCache makes a client request for the given `http.Request` and caches it if `CanCache`.
+// THe `ruleThrottler` may be nil, in which case the request will be unthrottled.
+func GetAndCache(
+	req *http.Request,
+	proxyURL *url.URL,
+	cacheKey string,
+	remapName string,
+	reqHeader http.Header,
+	reqTime time.Time,
+	strictRFC bool,
+	cache icache.Cache,
+	ruleThrottler thread.Throttler,
+	revalidateObj *cacheobj.CacheObj,
+	timeout time.Duration,
+	cacheFailure bool,
+	retryNum int,
+	retryCodes map[int]struct{},
+	transport *http.Transport,
+	reqID uint64,
+) *cacheobj.CacheObj {
+	// TODO this is awkward, with 'revalidateObj' indicating whether the request is a Revalidate. Should Getting and Caching be split up? How?
+	get := func() *cacheobj.CacheObj {
+		// TODO figure out why respReqTime isn't used by rules
+		log.Debugf("GetAndCache calling request %v %v %v %v %v (reqid %v)\n", req.Method, req.URL.Scheme, req.URL.Host, req.URL.EscapedPath(), req.Header, reqID)
+		// TODO Verify overriding the passed reqTime is the right thing to do
+		proxyURLStr := ""
+		if proxyURL != nil {
+			proxyURLStr = proxyURL.Host
+		}
+		if revalidateObj != nil {
+			req.Header.Set(ModifiedSinceHdr, revalidateObj.RespRespTime.Format(time.RFC1123))
+		} else {
+			req.Header.Del(ModifiedSinceHdr)
+		}
+		respCode, respHeader, respBody, reqTime, reqRespTime, err := web.Request(transport, req)
+		log.Debugf("GetAndCache web.Request URI %v %v %v cacheKey %v rule %v parent %v error %v reval %v code %v len(body) %v (reqid %v)\n", req.URL.Scheme, req.URL.Host, req.URL.EscapedPath(), cacheKey, remapName, proxyURLStr, err, revalidateObj != nil, respCode, len(respBody), reqID)
+
+		if err != nil {
+			log.Errorf("Parent error for URI %v %v %v cacheKey %v rule %v parent %v error %v (reqid %v)\n", req.URL.Scheme, req.URL.Host, req.URL.EscapedPath(), cacheKey, remapName, proxyURLStr, err, reqID)
+			code := CodeConnectFailure
+			body := []byte(http.StatusText(code))
+			return cacheobj.New(reqHeader, body, code, code, proxyURLStr, respHeader, reqTime, reqRespTime, reqRespTime, time.Time{})
+		}
+		if _, ok := retryCodes[respCode]; ok && !cacheFailure {
+			return cacheobj.New(reqHeader, respBody, respCode, respCode, proxyURLStr, respHeader, reqTime, reqRespTime, reqRespTime, time.Time{})
+		}
+
+		log.Debugf("GetAndCache request returned %v headers %+v (reqid %v)\n", respCode, respHeader, reqID)
+		respRespTime, ok := web.GetHTTPDate(respHeader, "Date")
+		if !ok {
+			log.Errorf("request %v returned no Date header - RFC Violation! Using local response timestamp (reqid %v)\n", req.RequestURI, reqID)
+			respRespTime = reqRespTime // if no Date was returned using the client response time simulates latency 0
+		}
+
+		lastModified, ok := web.GetHTTPDate(respHeader, "Last-Modified")
+		if !ok {
+			lastModified = respRespTime
+		}
+
+		obj := (*cacheobj.CacheObj)(nil)
+		log.Debugf("h.cache.Add %v (reqid %v)\n", cacheKey, reqID)
+		log.Debugf("GetAndCache respCode %v (reqid %v)\n", respCode, reqID)
+		if revalidateObj == nil || respCode != http.StatusNotModified {
+			log.Debugf("GetAndCache new %v (reqid %v)\n", cacheKey, reqID)
+			obj = cacheobj.New(reqHeader, respBody, respCode, respCode, proxyURLStr, respHeader, reqTime, reqRespTime, respRespTime, lastModified)
+			if !remap.CanCache(req.Method, reqHeader, respCode, respHeader, strictRFC) {
+				return obj // return without caching
+			}
+		} else {
+			log.Debugf("GetAndCache revalidating %v len(revalidateObj.Body) %v (reqid %v)\n", cacheKey, len(revalidateObj.Body), reqID)
+			// must copy, because this cache object may be concurrently read by other goroutines
+			newRespHeader := web.CopyHeader(revalidateObj.RespHeaders)
+			newRespHeader.Set("Date", respHeader.Get("Date"))
+			obj = &cacheobj.CacheObj{
+				Body:             revalidateObj.Body,
+				ReqHeaders:       revalidateObj.ReqHeaders,
+				RespHeaders:      newRespHeader,
+				RespCacheControl: revalidateObj.RespCacheControl,
+				Code:             revalidateObj.Code,
+				OriginCode:       respCode,
+				ProxyURL:         proxyURLStr,
+				ReqTime:          reqTime,
+				ReqRespTime:      reqRespTime,
+				RespRespTime:     respRespTime,
+				LastModified:     revalidateObj.LastModified,
+				Size:             revalidateObj.Size,
+			}
+		}
+		cache.Add(cacheKey, obj) // TODO store pointer?
+		return obj
+	}
+
+	c := (*cacheobj.CacheObj)(nil)
+	if ruleThrottler == nil {
+		log.Errorf("rule %v not in ruleThrottlers map. Requesting with no origin limit! (reqid %v)\n", remapName, reqID)
+		ruleThrottler = thread.NewNoThrottler()
+	}
+	ruleThrottler.Throttle(func() { c = get() })
+	return c
+}
diff --git a/grove/cachedata/cachedata.go b/grove/cachedata/cachedata.go
new file mode 100644
index 000000000..d627b3c11
--- /dev/null
+++ b/grove/cachedata/cachedata.go
@@ -0,0 +1,58 @@
+package cachedata
+
+/*
+   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.
+*/
+
+// cachedata exists as a package to avoid import cycles
+
+import (
+	"net/http"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+// ParentResponseData contains data about the parent/origin response.
+type ParentRespData struct {
+	Reuse            remapdata.Reuse
+	OriginCode       int
+	OriginReqSuccess bool
+	// OriginConnectFailed is whether the connection to the origin succeeded. It's possible to get a failure response from an origin, but have the connection succeed.
+	OriginConnectFailed bool
+	OriginBytes         uint64
+	ProxyStr            string
+}
+
+// HandlerData contains data generally held by the Handler, and known as soon as the request is received.
+type SrvrData struct {
+	Hostname string
+	Port     string
+	Scheme   string
+}
+
+type ReqData struct {
+	Req      *http.Request
+	Conn     *web.InterceptConn
+	ClientIP string
+	ReqTime  time.Time
+	ToFQDN   string
+}
+
+type RespData struct {
+	RespCode     int
+	BytesWritten uint64
+	RespSuccess  bool
+	CacheHit     bool
+}
diff --git a/grove/cacheobj/cacheobj.go b/grove/cacheobj/cacheobj.go
new file mode 100644
index 000000000..3e6b27f51
--- /dev/null
+++ b/grove/cacheobj/cacheobj.go
@@ -0,0 +1,63 @@
+package cacheobj
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+type CacheObj struct {
+	Body             []byte
+	ReqHeaders       http.Header
+	RespHeaders      http.Header
+	RespCacheControl web.CacheControl
+	Code             int
+	OriginCode       int
+	ProxyURL         string
+	ReqTime          time.Time // our client's time when the object was requested
+	ReqRespTime      time.Time // our client's time when the object was received
+	RespRespTime     time.Time // the origin server's Date time when the object was sent
+	LastModified     time.Time // the origin LastModified if it exists, or Date if it doesn't
+	Size             uint64
+}
+
+// ComputeSize computes the size of the given CacheObj. This computation is expensive, as the headers must be iterated over. Thus, the size should be computed once and stored, not computed on-the-fly for every new request for the cached object.
+func (c CacheObj) ComputeSize() uint64 {
+	// TODO include headers size
+	return uint64(len(c.Body))
+}
+
+func New(reqHeader http.Header, bytes []byte, code int, originCode int, proxyURL string, respHeader http.Header, reqTime time.Time, reqRespTime time.Time, respRespTime time.Time, lastModified time.Time) *CacheObj {
+	obj := &CacheObj{
+		Body:             bytes,
+		ReqHeaders:       reqHeader,
+		RespHeaders:      respHeader,
+		RespCacheControl: web.ParseCacheControl(respHeader),
+		Code:             code,
+		OriginCode:       originCode,
+		ProxyURL:         proxyURL,
+		ReqTime:          reqTime,
+		ReqRespTime:      reqRespTime,
+		RespRespTime:     respRespTime,
+		LastModified:     lastModified,
+	}
+	// copyHeader(reqHeader, &obj.reqHeaders)
+	// copyHeader(respHeader, &obj.respHeaders)
+	obj.Size = obj.ComputeSize()
+	return obj
+}
diff --git a/grove/chash/atsconsistenthash.go b/grove/chash/atsconsistenthash.go
new file mode 100644
index 000000000..7cf166a19
--- /dev/null
+++ b/grove/chash/atsconsistenthash.go
@@ -0,0 +1,144 @@
+package chash
+
+/*
+   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.
+*/
+
+import (
+	"fmt"
+	"math"
+	"strconv"
+
+	"github.com/dchest/siphash"
+)
+
+// This is specifically designed to match the Apache Traffic Server Parent Selection Consistent Hash, so that Grove deployed alongside ATS will hash to the same parent (mid-tier) caches, and thus result in the same mids caching the same content
+
+// Transliterated from https://raw.githubusercontent.com/apache/trafficserver/master/lib/ts/HashSip.cc
+// via https://github.com/floodyberry/siphash
+// via https://131002.net/siphash/
+
+// type HashRing interface {
+// 	Get(key string) string
+// 	// Add(val string)
+// 	// AddWeighted(val string, weight int)
+// }
+
+// type ATSHashRing struct {
+// }
+
+type ATSConsistentHash interface {
+	Insert(node *ATSConsistentHashNode, weight float64) error
+	String() string
+	// Lookup returns the found node, its map iterator, and whether the lookup wrapped
+	Lookup(name string) (OrderedMapUint64NodeIterator, bool, error)
+	LookupHash(hashVal uint64) (OrderedMapUint64NodeIterator, bool)
+	LookupIter(OrderedMapUint64NodeIterator) (OrderedMapUint64NodeIterator, bool)
+	First() OrderedMapUint64NodeIterator // debug
+}
+
+const DefaultSimpleATSConsistentHashReplicas = 1024
+
+type SimpleATSConsistentHash struct {
+	Replicas int
+	NodeMap  OrderedMapUint64Node
+}
+
+func NewSimpleATSConsistentHash(replicas int) ATSConsistentHash {
+	return &SimpleATSConsistentHash{Replicas: replicas, NodeMap: NewSimpleOrderedMapUint64Node()}
+}
+
+func round(f float64) int {
+	if math.Abs(f) < 0.5 {
+		return 0
+	}
+	return int(f + math.Copysign(0.5, f))
+}
+
+func (h *SimpleATSConsistentHash) String() string {
+	return h.NodeMap.String()
+}
+
+func (h *SimpleATSConsistentHash) Insert(node *ATSConsistentHashNode, weight float64) error {
+	numInserts := round(float64(h.Replicas) * weight)
+	keys := make([]uint64, numInserts)
+	vals := make([]*ATSConsistentHashNode, numInserts)
+	for i := 0; i < numInserts; i++ {
+		hashStr := ""
+		if node.ProxyURL != nil {
+			hashStr = strconv.Itoa(i) + "-" + node.ProxyURL.Hostname()
+		} else {
+			hashStr = strconv.Itoa(i) + "-" + node.Name
+		}
+		hashKey := siphash.Hash(0, 0, []byte(hashStr))
+		keys[i] = hashKey
+		vals[i] = node
+	}
+	err := h.NodeMap.InsertBulk(keys, vals)
+	return err
+}
+
+func (h *SimpleATSConsistentHash) First() OrderedMapUint64NodeIterator {
+	return h.NodeMap.First()
+}
+
+// Lookup returns the found node, its map iterator, and whether the lookup wrapped
+func (h *SimpleATSConsistentHash) Lookup(name string) (OrderedMapUint64NodeIterator, bool, error) {
+	iter := OrderedMapUint64NodeIterator(nil)
+
+	if name == "" {
+		// (*iter)++;
+		return nil, false, fmt.Errorf("lookup name is empty")
+	}
+
+	hashVal := siphash.Hash(0, 0, []byte(name))
+	iter = h.NodeMap.LowerBound(hashVal)
+
+	wrapped := false
+	if iter == nil {
+		wrapped = true
+		iter = h.NodeMap.First()
+	}
+
+	if wrapped && iter == nil {
+		return nil, false, fmt.Errorf("not found")
+	}
+
+	return iter, wrapped, nil
+
+}
+
+func (h *SimpleATSConsistentHash) LookupIter(i OrderedMapUint64NodeIterator) (OrderedMapUint64NodeIterator, bool) {
+	wrapped := false
+	if i == nil {
+		i = h.NodeMap.First()
+		wrapped = true
+	} else {
+		i = i.Next()
+	}
+	if i == nil {
+		i = h.NodeMap.First()
+		wrapped = true
+	}
+	return i, wrapped
+}
+
+func (h *SimpleATSConsistentHash) LookupHash(hashVal uint64) (OrderedMapUint64NodeIterator, bool) {
+	wrapped := false
+	iter := h.NodeMap.LowerBound(hashVal)
+	if iter == nil {
+		wrapped = true
+		iter = h.NodeMap.First()
+	}
+	return iter, wrapped
+}
diff --git a/grove/chash/atsconsistenthash_test.go b/grove/chash/atsconsistenthash_test.go
new file mode 100644
index 000000000..e67e310df
--- /dev/null
+++ b/grove/chash/atsconsistenthash_test.go
@@ -0,0 +1,91 @@
+package chash
+
+/*
+   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.
+*/
+
+import (
+	"testing"
+)
+
+func TestSimpleATSConsistentHashLookup(t *testing.T) {
+	replicas := 10
+
+	names := []string{"foo", "bar", "baz"}
+
+	nodes := []*ATSConsistentHashNode{}
+	for _, name := range names {
+		nodes = append(nodes, &ATSConsistentHashNode{Name: name})
+	}
+
+	inNodes := func(s string) bool {
+		for _, node := range nodes {
+			if node.Name == s {
+				return true
+			}
+		}
+		return false
+	}
+
+	h := NewSimpleATSConsistentHash(replicas)
+	for _, node := range nodes {
+		h.Insert(node, 1.0) // TODO test weights
+	}
+
+	lookup0 := "lookupasdf"
+	lookup1 := "lookupjkl;aasdfqeroipuzxcn;"
+	i, _, err := h.Lookup(lookup0)
+	if err != nil {
+		t.Errorf("ATSConsistentHash.Lookup expected nil error, actual %v", err)
+	}
+	lookup0Val := i.Val().Name
+	// fmt.Printf("ATSConsistentHash.Lookup0 got %v\n", i.Val().Name)
+	if !inNodes(i.Val().Name) {
+		t.Errorf("ATSConsistentHash.Lookup expected in %+v actual %v", names, i.Val().Name)
+	}
+
+	i, _, err = h.Lookup(lookup1)
+	if err != nil {
+		t.Errorf("ATSConsistentHash.Lookup expected nil error, actual %v", err)
+	}
+	lookup1Val := i.Val().Name
+	// fmt.Printf("ATSConsistentHash.Lookup1 got %v\n", i.Val().Name)
+	if !inNodes(i.Val().Name) {
+		t.Errorf("ATSConsistentHash.Lookup expected in %+v actual %v", names, i.Val().Name)
+	}
+
+	i, _, err = h.Lookup(lookup0)
+	if err != nil {
+		t.Errorf("ATSConsistentHash.Lookup expected nil error, actual %v", err)
+	}
+	if i.Val().Name != lookup0Val {
+		t.Errorf("ATSConsistentHash.Lookup expected consistent %v actual %v", lookup0Val, i.Val().Name)
+	}
+	// fmt.Printf("ATSConsistentHash.Lookup0 got %v\n", i.Val().Name)
+	if !inNodes(i.Val().Name) {
+		t.Errorf("ATSConsistentHash.Lookup expected in %+v actual %v", names, i.Val().Name)
+	}
+
+	i, _, err = h.Lookup(lookup1)
+	if err != nil {
+		t.Errorf("ATSConsistentHash.Lookup expected nil error, actual %v", err)
+	}
+	if i.Val().Name != lookup1Val {
+		t.Errorf("ATSConsistentHash.Lookup expected consistent %v actual %v", lookup1Val, i.Val().Name)
+	}
+	// fmt.Printf("ATSConsistentHash.Lookup1 got %v\n", i.Val().Name)
+	if !inNodes(i.Val().Name) {
+		t.Errorf("ATSConsistentHash.Lookup expected in %+v actual %v", names, i.Val().Name)
+	}
+
+}
diff --git a/grove/chash/atsorderedmap.go b/grove/chash/atsorderedmap.go
new file mode 100644
index 000000000..9052512ea
--- /dev/null
+++ b/grove/chash/atsorderedmap.go
@@ -0,0 +1,213 @@
+package chash
+
+/*
+   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.
+*/
+
+import (
+	"fmt"
+	"net/http"
+	"net/url"
+	"sort"
+	"strconv"
+	"time"
+)
+
+// func NewATSHashRing(vals []string) HashRing {
+
+// }
+
+// TODO move Weighted to a separate struct, `ATSWeightedHashRing`
+// func NewATSHashRingWeighted(vals map[string]int) HashRing {
+
+// }
+
+// func (h *ATSHashRing) Add(val string) {
+
+// }
+
+// func (h *ATSHashRing) AddWeighted(val string, weight int) {
+
+// }
+
+// ATSConsistentHashNode is an ATS ParentRecord
+type ATSConsistentHashNode struct {
+	Available bool
+	Name      string
+	ProxyURL  *url.URL
+	Transport *http.Transport
+	// pRecord fields (ParentSelection.h)
+	Hostname  string
+	Port      int
+	FailedAt  time.Time
+	FailCount int
+	UpAt      int
+	Scheme    string
+	Index     int
+	Weight    float64
+}
+
+func (n ATSConsistentHashNode) String() string {
+	return n.Name
+}
+
+type OrderedMapUint64NodeIterator interface {
+	Val() *ATSConsistentHashNode
+	Key() uint64
+	Next() OrderedMapUint64NodeIterator
+	NextWrap() OrderedMapUint64NodeIterator
+	Index() int
+}
+
+type OrderedMapUint64Node interface {
+	Insert(key uint64, val *ATSConsistentHashNode)
+	String() string
+	InsertBulk(keys []uint64, vals []*ATSConsistentHashNode) error
+	First() OrderedMapUint64NodeIterator
+	Last() OrderedMapUint64NodeIterator
+	At(index int) (uint64, *ATSConsistentHashNode)
+	LowerBound(val uint64) OrderedMapUint64NodeIterator
+}
+
+type SimpleOrderedMapUInt64Node struct {
+	M map[uint64]*ATSConsistentHashNode
+	O []uint64
+}
+
+func NewSimpleOrderedMapUint64Node() OrderedMapUint64Node {
+	return &SimpleOrderedMapUInt64Node{M: map[uint64]*ATSConsistentHashNode{}, O: []uint64{}}
+}
+
+type SortableUint64 []uint64
+
+func (a SortableUint64) Len() int           { return len(a) }
+func (a SortableUint64) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+func (a SortableUint64) Less(i, j int) bool { return a[i] < a[j] }
+
+func (m *SimpleOrderedMapUInt64Node) Insert(key uint64, val *ATSConsistentHashNode) {
+	m.M[key] = val
+	m.O = append(m.O, key)
+	sort.Sort(SortableUint64(m.O))
+}
+
+func (m *SimpleOrderedMapUInt64Node) InsertBulk(keys []uint64, vals []*ATSConsistentHashNode) error {
+	if len(keys) != len(vals) {
+		return fmt.Errorf("SimpleOrderedMapUInt64Node InsertBulk failed - len(keys) != len(vals)")
+	}
+
+	for i := 0; i < len(keys); i++ {
+		// fmt.Println("InsertBulk " + strconv.FormatUint(keys[i], 10) + ": " + vals[i].String() + " " + vals[i].ProxyURL.String())
+		m.M[keys[i]] = vals[i]
+	}
+
+	m.O = nil // clear, in case there were previous inserts
+	for k := range m.M {
+		m.O = append(m.O, k)
+	}
+	sort.Sort(SortableUint64(m.O))
+	return nil
+}
+
+func (m *SimpleOrderedMapUInt64Node) LowerBound(key uint64) OrderedMapUint64NodeIterator {
+	// TODO change to binary search
+	for i := 0; i < len(m.O); i++ {
+		if m.O[i] >= key {
+			return NewSimpleOrderedMapUint64NodeIterator(key, m.M[m.O[i]], i, m)
+		}
+	}
+	return nil
+}
+
+func (m *SimpleOrderedMapUInt64Node) String() string {
+	s := ""
+	i := m.First()
+	for {
+		if i == nil {
+			return s
+		}
+		s += strconv.FormatUint(i.Key(), 10) + ": " + i.Val().String() + " " + i.Val().ProxyURL.String() + "\n"
+		i = i.Next()
+	}
+}
+
+// First returns the iterator to the first element in the map. Returns nil if the map is empty
+func (m *SimpleOrderedMapUInt64Node) First() OrderedMapUint64NodeIterator {
+	if len(m.O) == 0 {
+		return nil
+	}
+	i := 0
+	key := m.O[0]
+	val := m.M[key]
+	return NewSimpleOrderedMapUint64NodeIterator(key, val, i, m)
+}
+
+// Last returns the iterator to the last element in the map. Returns nil if the map is empty
+func (m *SimpleOrderedMapUInt64Node) Last() OrderedMapUint64NodeIterator {
+	if len(m.O) == 0 {
+		return nil
+	}
+	i := len(m.O) - 1
+	key := m.O[i]
+	val := m.M[key]
+	return NewSimpleOrderedMapUint64NodeIterator(key, val, i, m)
+}
+
+func (m *SimpleOrderedMapUInt64Node) At(i int) (uint64, *ATSConsistentHashNode) {
+	key := m.O[i]
+	val := m.M[key]
+	return key, val
+}
+
+func NewSimpleOrderedMapUint64NodeIterator(key uint64, val *ATSConsistentHashNode, index int, m *SimpleOrderedMapUInt64Node) OrderedMapUint64NodeIterator {
+	return &SimpleOrderedMapUint64NodeIterator{key: key, val: val, index: index, m: m}
+}
+
+type SimpleOrderedMapUint64NodeIterator struct {
+	key   uint64
+	val   *ATSConsistentHashNode
+	index int
+	m     *SimpleOrderedMapUInt64Node
+}
+
+func (i *SimpleOrderedMapUint64NodeIterator) Val() *ATSConsistentHashNode { return i.val }
+func (i *SimpleOrderedMapUint64NodeIterator) Key() uint64                 { return i.key }
+
+func (i *SimpleOrderedMapUint64NodeIterator) Next() OrderedMapUint64NodeIterator {
+	next := i.index + 1
+	if next >= len(i.m.M) {
+		return nil
+	}
+	key, val := i.m.At(next)
+	return NewSimpleOrderedMapUint64NodeIterator(key, val, next, i.m)
+}
+
+func (i *SimpleOrderedMapUint64NodeIterator) NextWrap() OrderedMapUint64NodeIterator {
+	next := i.Next()
+	if next == nil {
+		return i.m.First()
+	}
+	return next
+}
+
+func (i *SimpleOrderedMapUint64NodeIterator) Prev() OrderedMapUint64NodeIterator {
+	prevI := i.index - 1
+	if prevI <= len(i.m.M) {
+		return nil
+	}
+	key, val := i.m.At(prevI)
+	return NewSimpleOrderedMapUint64NodeIterator(key, val, prevI, i.m)
+}
+
+func (i *SimpleOrderedMapUint64NodeIterator) Index() int {
+	return i.index
+}
diff --git a/grove/chash/atsorderedmap_test.go b/grove/chash/atsorderedmap_test.go
new file mode 100644
index 000000000..4b887e5f2
--- /dev/null
+++ b/grove/chash/atsorderedmap_test.go
@@ -0,0 +1,54 @@
+package chash
+
+/*
+   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.
+*/
+
+import (
+	"testing"
+)
+
+func TestSimpleOrderedMapUInt64Node(t *testing.T) {
+	vals := map[uint64]*ATSConsistentHashNode{
+		1: &ATSConsistentHashNode{Name: "foo"},
+		2: &ATSConsistentHashNode{Name: "bar"},
+		3: &ATSConsistentHashNode{Name: "baz"},
+	}
+
+	m := NewSimpleOrderedMapUint64Node()
+
+	for k, v := range vals {
+		m.Insert(k, v)
+	}
+
+	count := 0
+	for i := m.First(); i != nil; i = i.Next() {
+		count++
+		k := i.Key()
+		val := i.Val()
+
+		// fmt.Printf("OrderedMapUint64Node %v : %v\n", k, val)
+
+		valsVal, exists := vals[k]
+		if !exists {
+			t.Errorf("hash key %v was not inserted!", k)
+		}
+		if valsVal != val {
+			t.Errorf("hash key %v value expected %v actual %v", k, valsVal, val)
+		}
+		delete(vals, k)
+	}
+	if len(vals) != 0 {
+		t.Errorf("hash entries expected %+v actual nil", vals)
+	}
+}
diff --git a/grove/config/config.go b/grove/config/config.go
new file mode 100644
index 000000000..c282e476a
--- /dev/null
+++ b/grove/config/config.go
@@ -0,0 +1,121 @@
+package config
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+	"io/ioutil"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+const bytesPerGibibyte = 1024 * 1024 * 1024
+const bytesPerMebibyte = 1024 * 1024
+
+type Config struct {
+	// RFCCompliant determines whether `Cache-Control: no-cache` requests are honored. The ability to ignore `no-cache` is necessary to protect origin servers from DDOS attacks. In general, CDNs and caching proxies with the goal of origin protection should set RFCComplaint false. Cache with other goals (performance, load balancing, etc) should set RFCCompliant true.
+	RFCCompliant bool `json:"rfc_compliant"`
+	// Port is the HTTP port to serve on
+	Port      int `json:"port"`
+	HTTPSPort int `json:"https_port"`
+	// CacheSizeBytes is the size of the memory cache, in bytes.
+	CacheSizeBytes int    `json:"cache_size_bytes"`
+	RemapRulesFile string `json:"remap_rules_file"`
+	// ConcurrentRuleRequests is the number of concurrent requests permitted to a remap rule, that is, to an origin. Note this is overridden by any per-rule settings in the remap rules.
+	ConcurrentRuleRequests int    `json:"concurrent_rule_requests"`
+	CertFile               string `json:"cert_file"`
+	KeyFile                string `json:"key_file"`
+	InterfaceName          string `json:"interface_name"`
+	// ConnectionClose determines whether to send a `Connection: close` header. This is primarily designed for maintenance, to drain the cache of incoming requestors. This overrides rule-specific `connection-close: false` configuration, under the assumption that draining a cache is a temporary maintenance operation, and if connectionClose is true on the service and false on some rules, those rules' configuration is probably a permament setting whereas the operator probably wants to drain all connections if the global setting is true. If it's necessary to leave connection close false on some rules, set all other rules' connectionClose to true and leave the global connectionClose unset.
+	ConnectionClose bool `json:"connection_close"`
+
+	LogLocationError   string `json:"log_location_error"`
+	LogLocationWarning string `json:"log_location_warning"`
+	LogLocationInfo    string `json:"log_location_info"`
+	LogLocationDebug   string `json:"log_location_debug"`
+	LogLocationEvent   string `json:"log_location_event"`
+
+	ReqTimeoutMS         int `json:"parent_request_timeout_ms"` // TODO rename "parent_request" to distinguish from client requests
+	ReqKeepAliveMS       int `json:"parent_request_keep_alive_ms"`
+	ReqMaxIdleConns      int `json:"parent_request_max_idle_connections"`
+	ReqIdleConnTimeoutMS int `json:"parent_request_idle_connection_timeout_ms"`
+
+	ServerIdleTimeoutMS  int                    `json:"server_idle_timeout_ms"`
+	ServerWriteTimeoutMS int                    `json:"server_write_timeout_ms"`
+	ServerReadTimeoutMS  int                    `json:"server_read_timeout_ms"`
+	CacheFiles           map[string][]CacheFile `json:"cache_files"`
+	// FileMemBytes is the amount of memory to use as an LRU in front of each name in CacheFiles, that is, each named group of files. E.g. if there are 10 files, the amount of memory used will be 10*FileMemBytes+CacheSizeBytes.
+	FileMemBytes int `json:"file_mem_bytes"`
+}
+
+type CacheFile struct {
+	Path  string `json:"path"`
+	Bytes uint64 `json:"size_bytes"`
+}
+
+func (c Config) ErrorLog() log.LogLocation {
+	return log.LogLocation(c.LogLocationError)
+}
+func (c Config) WarningLog() log.LogLocation {
+	return log.LogLocation(c.LogLocationWarning)
+}
+func (c Config) InfoLog() log.LogLocation {
+	return log.LogLocation(c.LogLocationInfo)
+}
+func (c Config) DebugLog() log.LogLocation {
+	return log.LogLocation(c.LogLocationDebug)
+}
+func (c Config) EventLog() log.LogLocation {
+	return log.LogLocation(c.LogLocationEvent)
+}
+
+const MSPerSec = 1000
+
+// DefaultConfig is the default configuration for the application, if no configuration file is given, or if a given config setting doesn't exist in the config file.
+var DefaultConfig = Config{
+	RFCCompliant:           true,
+	Port:                   80,
+	HTTPSPort:              443,
+	CacheSizeBytes:         bytesPerGibibyte,
+	RemapRulesFile:         "remap.config",
+	ConcurrentRuleRequests: 100000,
+	ConnectionClose:        false,
+	LogLocationError:       log.LogLocationStderr,
+	LogLocationWarning:     log.LogLocationStdout,
+	LogLocationInfo:        log.LogLocationNull,
+	LogLocationDebug:       log.LogLocationNull,
+	LogLocationEvent:       log.LogLocationStdout,
+	ReqTimeoutMS:           30 * MSPerSec,
+	ReqKeepAliveMS:         30 * MSPerSec,
+	ReqMaxIdleConns:        100,
+	ReqIdleConnTimeoutMS:   90 * MSPerSec,
+	ServerIdleTimeoutMS:    10 * MSPerSec,
+	ServerWriteTimeoutMS:   3 * MSPerSec,
+	ServerReadTimeoutMS:    3 * MSPerSec,
+	FileMemBytes:           bytesPerMebibyte * 100,
+}
+
+// LoadConfig loads the given config file. If an empty string is passed, the default config is returned.
+func LoadConfig(fileName string) (Config, error) {
+	cfg := DefaultConfig
+	if fileName == "" {
+		return cfg, nil
+	}
+	configBytes, err := ioutil.ReadFile(fileName)
+	if err == nil {
+		err = json.Unmarshal(configBytes, &cfg)
+	}
+	return cfg, err
+}
diff --git a/grove/diskcache/diskcache.go b/grove/diskcache/diskcache.go
new file mode 100644
index 000000000..ae9ce35cf
--- /dev/null
+++ b/grove/diskcache/diskcache.go
@@ -0,0 +1,213 @@
+package diskcache
+
+/*
+   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.
+*/
+
+import (
+	"bytes"
+	"encoding/gob"
+	"errors"
+	"sync/atomic"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/lru"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+
+	bolt "github.com/coreos/bbolt"
+)
+
+type DiskCache struct {
+	db           *bolt.DB
+	sizeBytes    uint64
+	maxSizeBytes uint64
+	lru          *lru.LRU
+}
+
+const BucketName = "b"
+
+func New(path string, cacheSizeBytes uint64) (*DiskCache, error) {
+	db, err := bolt.Open(path, 0600, &bolt.Options{Timeout: 5 * time.Second})
+	if err != nil {
+		return nil, errors.New("opening database '" + path + "': " + err.Error())
+	}
+
+	err = db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucketIfNotExists([]byte(BucketName)); err != nil {
+			return errors.New("creating bucket: " + err.Error())
+		}
+		return nil
+	})
+	if err != nil {
+		return nil, errors.New("creating bucket for database '" + path + "': " + err.Error())
+	}
+
+	return &DiskCache{db: db, maxSizeBytes: cacheSizeBytes, lru: lru.NewLRU(), sizeBytes: 0}, nil
+}
+
+// ResetAfterRestart rebuilds the LRU with an arbirtrary order and sets sizeBytes. This seems crazy, but it is better than doing nothing, sice gc is based on the LRU and sizeBytes. In the future, we may want to periodically sync the LRU to disk, but we'll still need to iterate over all keys in the disk DB to avoid orphaning objects.
+// Note: this assumes the LRU is empty. Don't run twice
+func (c *DiskCache) ResetAfterRestart() {
+	go c.db.View(func(tx *bolt.Tx) error {
+		log.Infof("Starting cache recovery from disk for: %s... ", c.db.Path())
+		size := 0
+		b := tx.Bucket([]byte(BucketName))
+
+		cursor := b.Cursor()
+
+		for k, v := cursor.First(); k != nil; k, v = cursor.Next() {
+			c.lru.Add(string(k), uint64(len(v)))
+			size += len(v)
+		}
+
+		atomic.AddUint64(&c.sizeBytes, uint64(size))
+		log.Infof("Cache recovery from disk for %s done (%d bytes). ", c.db.Path(), c.sizeBytes)
+		return nil
+	})
+}
+
+// Add takes a key and value to add. Returns whether an eviction occurred
+// The size is taken to fulfill the Cache interface, but the DiskCache doesn't use it.
+// Instead, we compute size from the serialized bytes stored to disk.
+//
+// Note DiskCache.Add does garbage collection in a goroutine, and thus it is not possible to determine eviction without impacting performance. This always returns false.
+func (c *DiskCache) Add(key string, val *cacheobj.CacheObj) bool {
+	log.Debugf("DiskCache Add CALLED key '%+v' size '%+v'\n", key, val.Size)
+	eviction := false
+
+	buf := bytes.Buffer{}
+	if err := gob.NewEncoder(&buf).Encode(val); err != nil {
+		log.Errorln("DiskCache.Add encoding cache object: " + err.Error())
+		return eviction
+	}
+	valBytes := buf.Bytes()
+
+	err := c.db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte(BucketName))
+		if b == nil {
+			return errors.New("bucket does not exist")
+		}
+		return b.Put([]byte(key), valBytes)
+	})
+	if err != nil {
+		log.Errorln("DiskCache.Add inserting '" + key + "' in database: " + err.Error())
+		return eviction
+	}
+
+	c.lru.Add(key, uint64(len(valBytes)))
+
+	newSizeBytes := atomic.AddUint64(&c.sizeBytes, uint64(len(valBytes)))
+	if newSizeBytes > c.maxSizeBytes {
+		go c.gc(newSizeBytes)
+	}
+
+	log.Debugf("DiskCache Add SUCCESS key '%+v' size '%+v' valBytes '%+v' c.sizeBytes '%+v'\n", key, val.Size, len(valBytes), c.sizeBytes)
+	return eviction
+}
+
+// gc does garbage collection, deleting stored entries until the DiskCache's size is less than maxSizeBytes. This is threadsafe, and should be called in a goroutine to avoid blocking the caller.
+// The given cacheSizeBytes must be `c.Size()`; it's passed here, because gc should be called immediately after an insert updates the size, so it saves an atomic instruction to pass rather than calling Size() again.
+func (c *DiskCache) gc(cacheSizeBytes uint64) {
+	for cacheSizeBytes > c.maxSizeBytes {
+		log.Debugf("DiskCache.gc cacheSizeBytes %+v > c.maxSizeBytes %+v\n", cacheSizeBytes, c.maxSizeBytes)
+		key, sizeBytes, exists := c.lru.RemoveOldest() // TODO change lru to use strings
+		if !exists {
+			// should never happen
+			log.Errorf("sizeBytes %v > %v maxSizeBytes, but LRU is empty!? Setting cache size to 0!\n", cacheSizeBytes, c.maxSizeBytes)
+			atomic.StoreUint64(&c.sizeBytes, 0)
+			return
+		}
+
+		log.Debugf("DiskCache.gc deleting key '" + key + "'")
+		err := c.db.Update(func(tx *bolt.Tx) error {
+			b := tx.Bucket([]byte(BucketName))
+			if b == nil {
+				return errors.New("bucket does not exist")
+			}
+			b.Delete([]byte(key))
+
+			return b.Delete([]byte(key))
+		})
+		if err != nil {
+			log.Errorln("removing '" + key + "' from cache: " + err.Error())
+		}
+
+		cacheSizeBytes = atomic.AddUint64(&c.sizeBytes, ^uint64(sizeBytes-1)) // subtract sizeBytes
+	}
+}
+
+// Get takes a key, and returns its value, and whether it was found, and updates the lru-ness and hitcount
+func (c *DiskCache) Get(key string) (*cacheobj.CacheObj, bool) {
+	val, found := c.Peek(key)
+	if found {
+		// TODO JvD check to see if val.Size is good to use here.
+		c.lru.Add(key, val.Size) // TODO directly call c.ll.MoveToFront
+		log.Debugln("DiskCache.Get getting '" + key + "' from cache and updating LRU")
+		return val, true
+	}
+	return nil, false
+
+}
+
+// Peek takes a key, and returns its value, and whether it was found, without changing the lru-ness or hit-count
+func (c *DiskCache) Peek(key string) (*cacheobj.CacheObj, bool) {
+	log.Debugln("DiskCache.Get key '" + key + "'")
+	valBytes := []byte(nil)
+
+	err := c.db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte(BucketName))
+		if b == nil {
+			return errors.New("bucket does not exist")
+		}
+		valBytes = b.Get([]byte(key))
+		return nil
+	})
+	if err != nil {
+		log.Errorln("DiskCache.Peek getting '" + key + "' from cache: " + err.Error())
+		return nil, false
+	}
+
+	if valBytes == nil {
+		log.Debugln("DiskCache.Peek key '" + key + "' CACHE MISS")
+		return nil, false
+	}
+
+	buf := bytes.NewBuffer(valBytes)
+	val := cacheobj.CacheObj{}
+	if err := gob.NewDecoder(buf).Decode(&val); err != nil {
+		log.Errorln("DiskCache.Peek decoding '" + key + "' from cache: " + err.Error())
+		return nil, false
+	}
+
+	log.Debugln("DiskCache.Peek key '" + key + "' CACHE HIT")
+	return &val, true
+}
+
+func (c *DiskCache) Size() uint64 {
+	return atomic.LoadUint64(&c.sizeBytes)
+}
+
+func (c *DiskCache) Close() {
+	c.db.Close()
+}
+
+func (c *DiskCache) Keys() []string {
+	return c.lru.Keys()
+
+}
+
+func (c *DiskCache) Capacity() uint64 {
+	return c.maxSizeBytes
+}
diff --git a/grove/diskcache/multi.go b/grove/diskcache/multi.go
new file mode 100644
index 000000000..d877c2da1
--- /dev/null
+++ b/grove/diskcache/multi.go
@@ -0,0 +1,98 @@
+package diskcache
+
+/*
+   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.
+*/
+
+import (
+	"errors"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/config"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+
+	"github.com/dchest/siphash"
+)
+
+// MultiDiskCache is a disk cache using multiple files. It exists primarily to allow caching across multiple physical disks, but may be used for other purposes. For example, it may be more performant to use multiple files, or it may be advantageous to keep each remap rule in its own file. Keys are evenly distributed across the given files via consistent hashing.
+type MultiDiskCache []*DiskCache
+
+func NewMulti(files []config.CacheFile) (*MultiDiskCache, error) {
+	caches := make([]*DiskCache, len(files), len(files))
+	for i, file := range files {
+		cache, err := New(file.Path, file.Bytes)
+		if err != nil {
+			return nil, errors.New("creating disk cache '" + file.Path + "': " + err.Error())
+		}
+		cache.ResetAfterRestart() // should this be optional?
+		caches[i] = cache
+	}
+
+	mdc := MultiDiskCache(caches)
+	return &mdc, nil
+}
+
+// KeyIdx gets the consistent-hashed index of which DiskCache the key is mapped to.
+func (c *MultiDiskCache) keyIdx(key string) int {
+	return int(siphash.Hash(0, 0, []byte(key)) % uint64(len(*c)))
+}
+
+func (c *MultiDiskCache) Add(key string, val *cacheobj.CacheObj) bool {
+	i := c.keyIdx(key)
+	log.Debugf("MultiDiskCache.Add key '%+v' size '%+v' mapped to %+v\n", key, val.Size, i)
+	return (*c)[i].Add(key, val)
+}
+
+func (c *MultiDiskCache) Get(key string) (*cacheobj.CacheObj, bool) {
+	i := c.keyIdx(key)
+	log.Debugf("MultiDiskCache.Get key '%+v' mapped to %+v\n", key, i)
+	return (*c)[i].Get(key)
+}
+
+func (c *MultiDiskCache) Peek(key string) (*cacheobj.CacheObj, bool) {
+	i := c.keyIdx(key)
+	log.Debugf("MultiDiskCache.Get key '%+v' mapped to %+v\n", key, i)
+	return (*c)[i].Peek(key)
+}
+
+func (c *MultiDiskCache) Size() uint64 {
+	sum := uint64(0)
+	for _, cache := range *c {
+		sum += cache.Size()
+	}
+	return sum
+}
+
+func (c *MultiDiskCache) Close() {
+	for _, cache := range *c {
+		cache.Close()
+	}
+}
+
+func (c *MultiDiskCache) Keys() []string {
+	// TODO Fix this - each cache is an independent LRU, and the below doesn't make sense.
+	arr := make([]string, 0)
+	for _, cache := range *c {
+		arr = append(arr, cache.Keys()...)
+	}
+	return arr
+}
+
+func (c *MultiDiskCache) Capacity() uint64 {
+	sum := uint64(0)
+	for _, cache := range *c {
+		sum += cache.Capacity()
+	}
+	return sum
+}
diff --git a/grove/docker/Dockerfile b/grove/docker/Dockerfile
new file mode 100644
index 000000000..9bf9a4538
--- /dev/null
+++ b/grove/docker/Dockerfile
@@ -0,0 +1,32 @@
+# 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.
+
+# Example Build and Run:
+# docker build --rm --tag grove:0.1 --build-arg=RPM=grove-0.1.127-1.x86_64.rpm .
+#
+# docker run --name my-grove-cache --hostname my-grove-cache --net cdnet --env REMAP_PATH=/config/remap.json -v config:/config --detach grove:0.1
+#
+
+
+FROM centos/systemd
+
+RUN yum install -y initscripts epel-release openssl
+
+ARG RPM=grove.rpm
+ADD $RPM /
+RUN yum install -y /$(basename $RPM)
+
+RUN setcap 'cap_net_bind_service=+ep' /usr/sbin/grove
+
+EXPOSE 80 443
+ADD docker-entrypoint.sh /
+ENTRYPOINT /docker-entrypoint.sh
diff --git a/grove/docker/docker-entrypoint.sh b/grove/docker/docker-entrypoint.sh
new file mode 100755
index 000000000..c61c3e519
--- /dev/null
+++ b/grove/docker/docker-entrypoint.sh
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+
+# 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.
+
+# The following environment variables must be set, ordinarily by `docker run -e` arguments:
+envvars=( REMAP_PATH )
+for v in $envvars
+do
+	if [[ -z $$v ]]; then echo "$v is unset"; exit 1; fi
+done
+
+[ ! -z $PORT ]        || PORT=80
+[ ! -z $HTTPS_PORT ]  || HTTPS_PORT=443
+[ ! -z $CACHE_BYTES ] || CACHE_BYTES=100000000 # 100mb
+
+start() {
+	service grove start
+	exec tail -f /var/log/grove/error.log
+}
+
+init() {
+	cat > "/etc/grove/grove.cfg" <<- ENDOFMESSAGE
+{
+  "rfc_compliant":            false,
+  "port":                     $PORT,
+  "https_port":               $HTTPS_PORT,
+  "cache_size_bytes":         $CACHE_BYTES,
+  "remap_rules_file":         "/etc/grove/remap.json",
+  "concurrent_rule_requests": 100,
+  "connection_close":         false,
+  "interface_name":           "bond0",
+  "cert_file":                "/etc/grove/cert.pem",
+  "key_file":                 "/etc/grove/key.pem",
+
+  "log_location_error":   "/var/log/grove/error.log",
+  "log_location_warning": "/var/log/grove/error.log",
+  "log_location_info":    "null",
+  "log_location_debug":   "null",
+  "log_location_event":   "/opt/trafficserver/var/log/trafficserver/custom_ats_2.log",
+
+  "parent_request_timeout_ms":                 10000,
+  "parent_request_keep_alive_ms":              10000,
+  "parent_request_max_idle_connections":       10000,
+  "parent_request_idle_connection_timeout_ms": 10000,
+
+  "server_read_timeout_ms":  5000,
+  "server_write_timeout_ms": 5000,
+  "server_idle_timeout_ms":  5000
+}
+ENDOFMESSAGE
+
+	# TODO add Traffic Ops uri+user+pass+hostname as an option, rather than remap file
+	if [[ ! -z $REMAP_PATH ]]; then
+    cp $REMAP_PATH /etc/grove/remap.json
+  fi
+	mkdir -p /opt/trafficserver/var/log/trafficserver
+	mkdir -p /var/log/grove/
+	touch /var/log/grove/error.log
+
+	openssl req -newkey rsa:2048 -nodes -keyout /etc/grove/key.pem -x509 -days 3650 -out /etc/grove/cert.pem -subj "/C=US/ST=Colorado/L=Denver/O=MyCompany/CN=cdn.example.net"
+
+	# TODO add server to Traffic Ops, with env vars
+
+	echo "INITIALIZED=1" >> /etc/environment
+}
+
+source /etc/environment
+if [ -z "$INITIALIZED" ]; then init; fi
+start
diff --git a/grove/grove.cfg b/grove/grove.cfg
new file mode 100644
index 000000000..e9ca358ed
--- /dev/null
+++ b/grove/grove.cfg
@@ -0,0 +1,6 @@
+{
+  "rfc_compliant": false,
+  "port": 8080,
+  "cache_size_bytes": 50000,
+  "remap_rules_file": "./remap.json"
+}
diff --git a/grove/grove.go b/grove/grove.go
new file mode 100644
index 000000000..a610d466d
--- /dev/null
+++ b/grove/grove.go
@@ -0,0 +1,395 @@
+package main
+
+/*
+   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.
+*/
+
+import (
+	"context"
+	"crypto/tls"
+	"errors"
+	"flag"
+	"fmt"
+	"net"
+	"net/http"
+	"os"
+	"os/signal"
+	"reflect"
+	"runtime"
+	"runtime/pprof"
+	"strconv"
+	"strings"
+	"time"
+
+	"golang.org/x/net/http2"
+	"golang.org/x/sys/unix"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cache"
+	"github.com/apache/incubator-trafficcontrol/grove/config"
+	"github.com/apache/incubator-trafficcontrol/grove/diskcache"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+	"github.com/apache/incubator-trafficcontrol/grove/memcache"
+	"github.com/apache/incubator-trafficcontrol/grove/plugin"
+	"github.com/apache/incubator-trafficcontrol/grove/remap"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/stat"
+	"github.com/apache/incubator-trafficcontrol/grove/tiercache"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+const ShutdownTimeout = 60 * time.Second
+
+func main() {
+	runtime.GOMAXPROCS(32) // DEBUG
+	configFileName := flag.String("cfg", "", "The config file path")
+	pprof := flag.Bool("pprof", false, "Whether to profile")
+	showVersion := flag.Bool("version", false, "Print the application version")
+	flag.Parse()
+
+	if *showVersion {
+		fmt.Println(Version)
+		os.Exit(0)
+	}
+
+	if *configFileName == "" {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error starting service: The -cfg argument is required")
+		os.Exit(1)
+	}
+
+	cfg, err := config.LoadConfig(*configFileName)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error starting service: loading config: " + err.Error())
+		os.Exit(1)
+	}
+
+	eventW, errW, warnW, infoW, debugW, err := log.GetLogWriters(cfg)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error starting service: failed to create log writers: " + err.Error())
+		os.Exit(1)
+	}
+	log.Init(eventW, errW, warnW, infoW, debugW)
+
+	caches, err := createCaches(cfg.CacheFiles, uint64(cfg.FileMemBytes), uint64(cfg.CacheSizeBytes))
+	if err != nil {
+		log.Errorln("starting service: creating caches: " + err.Error())
+		os.Exit(1)
+	}
+
+	reqTimeout := time.Duration(cfg.ReqTimeoutMS) * time.Millisecond
+	reqKeepAlive := time.Duration(cfg.ReqKeepAliveMS) * time.Millisecond
+	reqMaxIdleConns := cfg.ReqMaxIdleConns
+	reqIdleConnTimeout := time.Duration(cfg.ReqIdleConnTimeoutMS) * time.Millisecond
+	baseTransport := remap.NewRemappingTransport(reqTimeout, reqKeepAlive, reqMaxIdleConns, reqIdleConnTimeout)
+
+	plugins := plugin.Get()
+	remapper, err := remap.LoadRemapper(cfg.RemapRulesFile, plugins.LoadFuncs(), caches, baseTransport)
+	if err != nil {
+		log.Errorf("starting service: loading remap rules: %v\n", err)
+		os.Exit(1)
+	}
+
+	certs, err := loadCerts(remapper.Rules())
+	if err != nil {
+		log.Errorf("starting service: loading certificates: %v\n", err)
+		os.Exit(1)
+	}
+	defaultCert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile)
+	if err != nil {
+		log.Errorf("starting service: loading default certificate: %v\n", err)
+		os.Exit(1)
+	}
+	certs = append(certs, defaultCert)
+
+	httpListener, httpConns, httpConnStateCallback, err := web.InterceptListen("tcp", fmt.Sprintf(":%d", cfg.Port))
+	if err != nil {
+		log.Errorf("creating HTTP listener %v: %v\n", cfg.Port, err)
+		os.Exit(1)
+	}
+
+	httpsConns := (*web.ConnMap)(nil)
+	httpsServer := (*http.Server)(nil)
+	httpsListener := net.Listener(nil)
+	httpsConnStateCallback := (func(net.Conn, http.ConnState))(nil)
+	tlsConfig := (*tls.Config)(nil)
+	if cfg.CertFile != "" && cfg.KeyFile != "" {
+		if httpsListener, httpsConns, httpsConnStateCallback, tlsConfig, err = web.InterceptListenTLS("tcp", fmt.Sprintf(":%d", cfg.HTTPSPort), certs); err != nil {
+			log.Errorf("creating HTTPS listener %v: %v\n", cfg.HTTPSPort, err)
+			return
+		}
+	}
+
+	// TODO pass total size for all file groups?
+	stats := stat.New(remapper.Rules(), caches, uint64(cfg.CacheSizeBytes), httpConns, httpsConns, Version)
+
+	buildHandler := func(scheme string, port string, conns *web.ConnMap, stats stat.Stats, pluginContext map[string]*interface{}) *cache.HandlerPointer {
+		return cache.NewHandlerPointer(cache.NewHandler(
+			remapper,
+			uint64(cfg.ConcurrentRuleRequests),
+			stats,
+			scheme,
+			port,
+			conns,
+			cfg.RFCCompliant,
+			cfg.ConnectionClose,
+			plugins,
+			pluginContext,
+			httpConns,
+			httpsConns,
+			cfg.InterfaceName,
+		))
+	}
+
+	pluginContext := map[string]*interface{}{}
+
+	httpHandler := buildHandler("http", strconv.Itoa(cfg.Port), httpConns, stats, pluginContext)
+	httpsHandler := buildHandler("https", strconv.Itoa(cfg.HTTPSPort), httpsConns, stats, pluginContext)
+
+	idleTimeout := time.Duration(cfg.ServerIdleTimeoutMS) * time.Millisecond
+	readTimeout := time.Duration(cfg.ServerReadTimeoutMS) * time.Millisecond
+	writeTimeout := time.Duration(cfg.ServerWriteTimeoutMS) * time.Millisecond
+
+	plugins.OnStartup(remapper.PluginCfg(), pluginContext, plugin.StartupData{Config: cfg, Shared: remapper.PluginSharedCfg()})
+
+	// TODO add config to not serve HTTP (only HTTPS). If port is not set?
+	httpServer := startServer(httpHandler, httpListener, httpConnStateCallback, nil, cfg.Port, idleTimeout, readTimeout, writeTimeout, "http")
+
+	if cfg.CertFile != "" && cfg.KeyFile != "" {
+		httpsServer = startServer(httpsHandler, httpsListener, httpsConnStateCallback, tlsConfig, cfg.HTTPSPort, idleTimeout, readTimeout, writeTimeout, "https")
+	}
+
+	reloadConfig := func() {
+		log.Infoln("reloading config")
+		err := error(nil)
+		oldCfg := cfg
+		cfg, err = config.LoadConfig(*configFileName)
+		if err != nil {
+			log.Errorln("reloading config: failed to load config file, keeping existing config: " + err.Error())
+			cfg = oldCfg
+			return
+		}
+		eventW, errW, warnW, infoW, debugW, err := log.GetLogWriters(cfg)
+		if err != nil {
+			log.Errorln("reloading config: failed to get log writers from '" + *configFileName + "', keeping existing log locations: " + err.Error())
+		} else {
+			log.Init(eventW, errW, warnW, infoW, debugW)
+		}
+
+		// TODO add cache file reloading
+		// The problem is, the disk db needs file locks, so there's no way to close and create new files without making all requests cache miss in the meantime.
+		// Thus, the file paths must be kept, diffed, only removed paths' dbs closed, only new paths opened, and dbs for existing paths passed into the new caches object.
+		if cachesChanged(oldCfg, cfg) {
+			log.Warnln("reloading config: caches changed in new config! Dynamic cache reloading is not supported! Old cache files and sizes will be used, and new cache config will NOT be loaded! Restart service to apply cache changes!")
+		}
+
+		oldRemapper := remapper
+		remapper, err = remap.LoadRemapper(cfg.RemapRulesFile, plugins.LoadFuncs(), caches, baseTransport)
+		if err != nil {
+			log.Errorln("reloading config: failed to load remap rules, keeping existing rules: " + err.Error())
+			remapper = oldRemapper
+			return
+		}
+
+		if cfg.Port != oldCfg.Port {
+			if httpListener, httpConns, httpConnStateCallback, err = web.InterceptListen("tcp", fmt.Sprintf(":%d", cfg.Port)); err != nil {
+				log.Errorf("reloading config: creating HTTP listener %v: %v\n", cfg.Port, err)
+				return
+			}
+		}
+
+		if (cfg.CertFile != oldCfg.CertFile || cfg.KeyFile != oldCfg.KeyFile) && cfg.HTTPSPort != oldCfg.HTTPSPort {
+			log.Warnln("config certificate changed, but port did not. Cannot recreate listener on same port without stopping the service. Restart the service to load the new certificate.")
+		}
+
+		if cfg.HTTPSPort != oldCfg.HTTPSPort {
+			if httpsListener, httpsConns, httpsConnStateCallback, tlsConfig, err = web.InterceptListenTLS("tcp", fmt.Sprintf(":%d", cfg.HTTPSPort), certs); err != nil {
+				log.Errorf("creating HTTPS listener %v: %v\n", cfg.HTTPSPort, err)
+			}
+		}
+
+		stats = stat.New(remapper.Rules(), caches, uint64(cfg.CacheSizeBytes), httpConns, httpsConns, Version) // TODO copy stats from old stats object?
+
+		httpCacheHandler := cache.NewHandler(
+			remapper,
+			uint64(cfg.ConcurrentRuleRequests),
+			stats,
+			"http",
+			strconv.Itoa(cfg.Port),
+			httpConns,
+			cfg.RFCCompliant,
+			cfg.ConnectionClose,
+			plugins,
+			pluginContext,
+			httpConns,
+			httpsConns,
+			cfg.InterfaceName,
+		)
+		httpHandler.Set(httpCacheHandler)
+
+		httpsCacheHandler := cache.NewHandler(
+			remapper,
+			uint64(cfg.ConcurrentRuleRequests),
+			stats,
+			"https",
+			strconv.Itoa(cfg.HTTPSPort),
+			httpsConns,
+			cfg.RFCCompliant,
+			cfg.ConnectionClose,
+			plugins,
+			pluginContext,
+			httpConns,
+			httpsConns,
+			cfg.InterfaceName,
+		)
+		httpsHandler.Set(httpsCacheHandler)
+
+		if cfg.Port != oldCfg.Port {
+			ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeout)
+			defer cancel()
+			if err := httpServer.Shutdown(ctx); err != nil {
+				if err == context.DeadlineExceeded {
+					log.Errorf("closing http server: connections didn't close gracefully in %v, forcefully closing.\n", ShutdownTimeout)
+					httpServer.Close()
+				} else {
+					log.Errorf("closing http server: %v\n", err)
+				}
+
+			}
+			httpServer = startServer(httpHandler, httpListener, httpConnStateCallback, nil, cfg.Port, idleTimeout, readTimeout, writeTimeout, "http")
+		}
+
+		if (httpsServer == nil || cfg.HTTPSPort != oldCfg.HTTPSPort) && cfg.CertFile != "" && cfg.KeyFile != "" {
+			if httpsServer != nil {
+				ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeout)
+				defer cancel()
+				if err := httpsServer.Shutdown(ctx); err != nil {
+					if err == context.DeadlineExceeded {
+						log.Errorf("closing https server: connections didn't close gracefully in %v, forcefully closing.\n", ShutdownTimeout)
+						httpServer.Close()
+					} else {
+						log.Errorf("closing https server: %v\n", err)
+					}
+				}
+			}
+
+			httpsServer = startServer(httpsHandler, httpsListener, httpsConnStateCallback, tlsConfig, cfg.HTTPSPort, idleTimeout, readTimeout, writeTimeout, "https")
+		}
+	}
+
+	if *pprof {
+		profile()
+	}
+	signalReloader(unix.SIGHUP, reloadConfig)
+}
+
+func profile() {
+	go func() {
+		count := 0
+		for {
+			count++
+			filename := fmt.Sprintf("grove%d.pprof", count)
+			f, err := os.Create(filename)
+			if err != nil {
+				log.Errorf("creating profile: %v\n", err)
+				os.Exit(1)
+			}
+			pprof.StartCPUProfile(f)
+			time.Sleep(time.Minute)
+			pprof.StopCPUProfile()
+			f.Close()
+		}
+	}()
+}
+
+func signalReloader(sig os.Signal, f func()) {
+	c := make(chan os.Signal, 1)
+	signal.Notify(c, sig)
+	for range c {
+		f()
+	}
+}
+
+// startServer starts an HTTP or HTTPS server on the given port, and returns it.
+func startServer(handler http.Handler, listener net.Listener, connState func(net.Conn, http.ConnState), tlsConfig *tls.Config, port int, idleTimeout time.Duration, readTimeout time.Duration, writeTimeout time.Duration, protocol string) *http.Server {
+
+	server := &http.Server{
+		Handler:      handler,
+		TLSConfig:    tlsConfig,
+		Addr:         fmt.Sprintf(":%d", port),
+		ConnState:    connState,
+		IdleTimeout:  idleTimeout,
+		ReadTimeout:  readTimeout,
+		WriteTimeout: writeTimeout,
+	}
+
+	// TODO configurable H2 timeouts and buffer sizes
+	h2Conf := &http2.Server{
+		IdleTimeout: idleTimeout,
+	}
+	if err := http2.ConfigureServer(server, h2Conf); err != nil {
+		log.Errorln(" server configuring HTTP/2: " + err.Error())
+	}
+
+	go func() {
+		log.Infof("listening on %s://%d\n", protocol, port)
+		if err := server.Serve(listener); err != nil {
+			log.Errorf("serving %s port %v: %v\n", strings.ToUpper(protocol), port, err)
+		}
+	}()
+	return server
+}
+
+func loadCerts(rules []remapdata.RemapRule) ([]tls.Certificate, error) {
+	certs := []tls.Certificate{}
+	for _, rule := range rules {
+		if rule.CertificateFile == "" && rule.CertificateKeyFile == "" {
+			continue
+		}
+		if rule.CertificateFile == "" {
+			return nil, errors.New("rule " + rule.Name + " has a certificate but no key, using default certificate\n")
+		}
+		if rule.CertificateKeyFile == "" {
+			return nil, errors.New("rule " + rule.Name + " has a key but no certificate, using default certificate\n")
+		}
+
+		cert, err := tls.LoadX509KeyPair(rule.CertificateFile, rule.CertificateKeyFile)
+		if err != nil {
+			return nil, errors.New("loading rule " + rule.Name + " certificate: " + err.Error() + "\n")
+		}
+		certs = append(certs, cert)
+	}
+	return certs, nil
+}
+
+// createCaches creates the caches specified in the config. The nameFiles is the map of names to groups of files, nameMemBytes is the amount of memory to use for each named group, and memCacheBytes is the amount of memory to use for the default memory cache.
+func createCaches(nameFiles map[string][]config.CacheFile, nameMemBytes uint64, memCacheBytes uint64) (map[string]icache.Cache, error) {
+	caches := map[string]icache.Cache{}
+	caches[""] = memcache.New(memCacheBytes) // default empty names to the mem cache
+
+	for name, files := range nameFiles {
+		multiDiskCache, err := diskcache.NewMulti(files)
+		if err != nil {
+			return nil, errors.New("creating cache '" + name + "': " + err.Error())
+		}
+		caches[name] = tiercache.New(memcache.New(nameMemBytes), multiDiskCache)
+	}
+
+	return caches, nil
+}
+
+func cachesChanged(oldCfg, newCfg config.Config) bool {
+	return oldCfg.FileMemBytes == newCfg.FileMemBytes &&
+		oldCfg.CacheSizeBytes != newCfg.CacheSizeBytes &&
+		!reflect.DeepEqual(oldCfg.CacheFiles, newCfg.CacheFiles)
+}
diff --git a/grove/grovetccfg/README.md b/grove/grovetccfg/README.md
new file mode 100644
index 000000000..a251a2170
--- /dev/null
+++ b/grove/grovetccfg/README.md
@@ -0,0 +1,64 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you 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.
+-->
+
+# grovetccfg
+
+Traffic Control configuration generator for the Grove HTTP caching proxy.
+
+# Building
+
+1. Install and set up a Golang development environment.
+    * See https://golang.org/doc/install
+2. Clone this repository into your GOPATH.
+```bash
+mkdir -p $GOPATH/src/github.com/apache/incubator-trafficcontrol
+cd $GOPATH/src/github.com/apache/incubator-trafficcontrol
+git clone https://github.com/apache/incubator-trafficcontrol/grove
+```
+3. Build the application
+```bash
+cd $GOPATH/src/github.com/apache/incubator-trafficcontrol/grove/grovetccfg
+go build
+```
+5. Install and configure an RPM development environment
+   * See https://wiki.centos.org/HowTos/SetupRpmBuildEnvironment
+4. Build the RPM
+```bash
+./build/build_rpm.sh
+```
+
+# Running
+
+The `grovetccfg` tool has an RPM, but no service or config files. It must be run manually, even after installing the RPM. Consider running the tool in a cron job.
+
+Example:
+
+`./grovetccfg -api=1.2 -host my-http-cache -insecure -touser carpenter -topass 'walrus' -tourl https://cdn.example.net -pretty > remap.json`
+
+Flags:
+
+| Flag | Description |
+| --- | --- |
+| `api` | The Traffic Ops API version to use. The default is 1.2. If 1.3 is passed, it will use a newer and more efficient endpoint. |
+| `host` | The Traffic Ops server to create configuration from. This must be a cache server in Traffic Ops. |
+| `insecure` | Whether to ignore certificate errors when connecting to Traffic Ops |
+| `touser` | The Traffic Ops user to use. |
+| `topass` | The Traffic Ops user password. |
+| `tourl` | The Traffic Ops URL, including the scheme and fully qualified domain name. |
+| `pretty` | Whether to pretty-print JSON |
diff --git a/grove/grovetccfg/build/build_rpm.sh b/grove/grovetccfg/build/build_rpm.sh
new file mode 100755
index 000000000..bb55aa9ae
--- /dev/null
+++ b/grove/grovetccfg/build/build_rpm.sh
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+# 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.
+
+BUILDDIR="$HOME/rpmbuild"
+
+VERSION=`cat ./../VERSION`.`git rev-list --all --count`
+
+# prep build environment
+rm -rf $BUILDDIR
+mkdir -p $BUILDDIR/{BUILD,RPMS,SOURCES}
+echo "$BUILDDIR" > ~/.rpmmacros
+
+# get traffic_ops client
+# godir=src/github.com/apache/incubator-trafficcontrol/traffic_ops/client
+# ( mkdir -p "$godir" && \
+#   cd "$godir" && \
+#   cp -r ${GOPATH}/${godir}/* . && \
+#   go get -v \
+# ) || { echo "Could not build go program at $(pwd): $!"; exit 1; }
+
+# build
+go build -v
+
+# tar
+tar -cvzf $BUILDDIR/SOURCES/grovetccfg-${VERSION}.tgz grovetccfg
+
+# build RPM
+rpmbuild --define "version ${VERSION}" -ba build/grovetccfg.spec
+
+# copy build RPM to .
+cp $BUILDDIR/RPMS/x86_64/grovetccfg-${VERSION}-1.x86_64.rpm .
diff --git a/grove/grovetccfg/build/grovetccfg.spec b/grove/grovetccfg/build/grovetccfg.spec
new file mode 100644
index 000000000..4deb440cd
--- /dev/null
+++ b/grove/grovetccfg/build/grovetccfg.spec
@@ -0,0 +1,46 @@
+# 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.
+
+Summary: Grove HTTP Caching Proxy Traffic Control config generator
+Name: grovetccfg
+Version: %{version}
+Release: 1
+License: Apache License, Version 2.0
+Group: Base System/System Tools
+Prefix: /usr/sbin/%{name}
+Source: %{_sourcedir}/%{name}-%{version}.tgz
+URL: https://github.com/apache/incubator-trafficcontrol/%{name}
+Distribution: CentOS Linux
+Vendor: Apache Software Foundation
+BuildRoot: %{buildroot}
+
+# %define PACKAGEDIR %{prefix}
+
+%description
+A Traffic Control config generator for the Grove HTTP Caching Proxy
+
+%prep
+
+%build
+tar -xvzf %{_sourcedir}/%{name}-%{version}.tgz --directory %{_builddir}
+
+%install
+rm -rf %{buildroot}/usr/sbin/%{name}
+mkdir -p %{buildroot}/usr/sbin/
+cp -p %{name} %{buildroot}/usr/sbin/
+
+%clean
+echo "cleaning"
+rm -r -f %{buildroot}
+
+%files
+/usr/sbin/%{name}
diff --git a/grove/grovetccfg/grovetccfg.go b/grove/grovetccfg/grovetccfg.go
new file mode 100644
index 000000000..32da4b372
--- /dev/null
+++ b/grove/grovetccfg/grovetccfg.go
@@ -0,0 +1,974 @@
+package main
+
+/*
+   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.
+*/
+
+import (
+	"compress/gzip"
+	"encoding/base64"
+	"encoding/json"
+	"errors"
+	"flag"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"net"
+	"net/url"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	tcv13 "github.com/apache/incubator-trafficcontrol/lib/go-tc/v13"
+	to "github.com/apache/incubator-trafficcontrol/traffic_ops/client"
+
+	"github.com/apache/incubator-trafficcontrol/grove/config"
+	"github.com/apache/incubator-trafficcontrol/grove/remap"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+// Duplicating Hdr and ModHdrs here for now...
+// Seems cleaner than dragging it up from some arbitrary place in plugins
+
+const Version = "0.1"
+const UserAgent = "grove-tc-cfg/" + Version
+const TrafficOpsTimeout = time.Second * 90
+const DefaultCertificateDir = "/etc/grove/ssl"
+const GroveConfigPath = "/etc/grove/grove.cfg"
+
+func AvailableStatuses() map[string]struct{} {
+	return map[string]struct{}{
+		"reported": {},
+		"online":   {},
+	}
+}
+
+func GetRemapPath() (string, error) {
+	cfg, err := config.LoadConfig(GroveConfigPath)
+	if err != nil {
+		return "", errors.New("loading Grove config file: " + err.Error())
+	}
+	return cfg.RemapRulesFile, nil
+}
+
+// CopyAndGzipFile reads the src file, gzips the contents, and writes the result to dst.
+func CopyAndGzipFile(src, dst string) error {
+	srcF, err := os.Open(src)
+	if err != nil {
+		return errors.New("opening source file: " + err.Error())
+	}
+	defer srcF.Close()
+	dstF, err := os.Create(dst)
+	if err != nil {
+		return errors.New("creating destination file: " + err.Error())
+	}
+	defer dstF.Close()
+
+	dstFGzip := gzip.NewWriter(dstF)
+
+	if _, err = io.Copy(dstFGzip, srcF); err != nil {
+		return errors.New("copying source to destination: " + err.Error())
+	}
+	if err := dstFGzip.Close(); err != nil {
+		return errors.New("closing destination gzip writer: " + err.Error())
+	}
+	if err := dstF.Sync(); err != nil {
+		return errors.New("flushing copy to destination: " + err.Error())
+	}
+	return nil
+}
+
+// BackupFile copies the given file to a new file in the subdirectory "/remap_history", with the name suffixed by the current timestamp. Returns nil if the given file doesn't exist (nothing to back up).
+func BackupFile(path string) error {
+	if _, err := os.Stat(path); os.IsNotExist(err) {
+		return nil
+	}
+
+	fileTimeFormat := "2006-01-02T15_04_05_999999999Z07_00" // this is time.RFC3339Nano with : replaced by _
+	backupDir := filepath.Join(filepath.Dir(path), "remap_history")
+	backupFile := filepath.Base(path) + "." + time.Now().Format(fileTimeFormat) + ".gz"
+	backupPath := filepath.Join(backupDir, backupFile)
+
+	os.MkdirAll(backupDir, os.ModePerm)
+
+	if err := CopyAndGzipFile(path, backupPath); err != nil {
+		return errors.New("backuping up remap file: " + err.Error())
+	}
+	return nil
+}
+
+func NewFilename(path string) string {
+	return path + ".new"
+}
+
+func WriteNewFile(path string, bts []byte) error {
+	newPath := NewFilename(path)
+	f, err := os.Create(newPath)
+	if err != nil {
+		return errors.New("creating file: " + err.Error())
+	}
+	defer f.Close()
+	if _, err := f.Write(bts); err != nil {
+		return errors.New("writing file: " + err.Error())
+	}
+	if err := f.Sync(); err != nil {
+		return errors.New("flushing file: " + err.Error())
+	}
+	return nil
+}
+
+// WriteAndBackup creates a backup of the existing file at the given path, then writes the given bytes to the path. The write is fail-safe on operating systems with atomic file rename (Linux is).
+func WriteAndBackup(path string, bts []byte) error {
+	if err := BackupFile(path); err != nil {
+		return errors.New("backing up file: " + err.Error())
+	}
+	if err := WriteNewFile(path, bts); err != nil {
+		return errors.New("writing new file: " + err.Error())
+	}
+	if err := os.Rename(NewFilename(path), path); err != nil {
+		return errors.New("copying new file to real location: " + err.Error())
+	}
+	return nil
+}
+
+// hasUpdatePending returns whether an update is pending, the revalPending status (which will be needed later in the clear update POST), and any error.
+func hasUpdatePending(toc *to.Session, hostname string) (bool, bool, error) {
+	upd, _, err := toc.GetUpdate(hostname)
+	if err != nil {
+		return false, false, errors.New("getting update from Traffic Ops: " + err.Error())
+	}
+	return upd.UpdatePending, upd.RevalPending, nil
+}
+
+// clearUpdatePending clears the given host's update pending flag in Traffic Ops. It takes the host to clear, and the old revalPending flag to send.
+func clearUpdatePending(toc *to.Session, hostname string, revalPending bool) error {
+	revalPendingPostVal := 0
+	if revalPending == false {
+		revalPendingPostVal = to.UpdateStatusClear
+	} else {
+		revalPendingPostVal = to.UpdateStatusPending
+	}
+	_, err := toc.SetUpdate(hostname, to.UpdateStatusClear, revalPendingPostVal)
+	if err != nil {
+		return errors.New("setting update pending on Traffic Ops: " + err.Error())
+	}
+	return nil
+}
+
+func main() {
+	toURL := flag.String("tourl", "", "The Traffic Ops URL")
+	toUser := flag.String("touser", "", "The Traffic Ops username")
+	toPass := flag.String("topass", "", "The Traffic Ops password")
+	pretty := flag.Bool("pretty", false, "Whether to pretty-print output")
+	ignoreUpdateFlag := flag.Bool("ignore-update-flag", false, "Whether to fetch and apply the config, without checking or updating the Traffic Ops Update Pending flag")
+	host := flag.String("host", "", "The hostname of the server whose config to generate")
+	// api := flag.String("api", "1.2", "API version. Determines whether to use /api/1.3/configs/ or older, less efficient 1.2 APIs")
+	toInsecure := flag.Bool("insecure", false, "Whether to allow invalid certificates with Traffic Ops")
+	certDir := flag.String("certdir", DefaultCertificateDir, "Directory to save certificates to")
+	flag.Parse()
+
+	useCache := false
+	toc, _, err := to.LoginWithAgent(*toURL, *toUser, *toPass, *toInsecure, UserAgent, useCache, TrafficOpsTimeout)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error connecting to Traffic Ops: " + err.Error())
+		os.Exit(1)
+	}
+
+	revalPendingStatus := false
+	if !*ignoreUpdateFlag {
+		needsUpdate := false
+		needsUpdate, revalPendingStatus, err = hasUpdatePending(toc, *host)
+		if err != nil {
+			fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error checking Traffic Ops update pending: " + err.Error())
+			os.Exit(1)
+		}
+		if !needsUpdate {
+			os.Exit(0) // if no error and no update necessary, return success and print nothing
+		}
+	}
+
+	rules := remap.RemapRules{}
+	// if *api == "1.3" {
+	// 	rules, err = createRulesNewAPI(toc, *host, *certDir)
+	// } else {
+	rules, err = createRulesOldAPI(toc, *host, *certDir) // TODO remove once 1.3 / traffic_ops_golang is deployed to production.
+	// }
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error creating rules: " + err.Error())
+		os.Exit(1)
+	}
+
+	jsonRules, err := remap.RemapRulesToJSON(rules)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error creating JSON Remap Rules: " + err.Error())
+		os.Exit(1)
+	}
+
+	bts := []byte{}
+	if *pretty {
+		bts, err = json.MarshalIndent(jsonRules, "", "  ")
+	} else {
+		bts, err = json.Marshal(jsonRules)
+	}
+
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error marshalling rules JSON: " + err.Error())
+		os.Exit(1)
+	}
+
+	// TODO add app/option to print config to stdout
+
+	remapPath, err := GetRemapPath()
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting remap config path: " + err.Error())
+		os.Exit(1)
+	}
+
+	if err := WriteAndBackup(remapPath, bts); err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error writing new config file: " + err.Error())
+		os.Exit(1)
+	}
+
+	if err := exec.Command("service", "grove", "reload").Run(); err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error restarting grove service (but successfully updated config file): " + err.Error())
+		os.Exit(2)
+	}
+
+	if !*ignoreUpdateFlag {
+		if err := clearUpdatePending(toc, *host, revalPendingStatus); err != nil {
+			fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error clearing update pending flag in Traffic Ops (but successfully updated config): " + err.Error())
+			os.Exit(3)
+		}
+	}
+
+	os.Exit(0)
+}
+
+func createRulesOldAPI(toc *to.Session, host string, certDir string) (remap.RemapRules, error) {
+	cachegroupsArr, err := toc.CacheGroups()
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops Cachegroups: " + err.Error())
+		os.Exit(1)
+	}
+	cachegroups := makeCachegroupsNameMap(cachegroupsArr)
+
+	serversArr, err := toc.Servers()
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops Servers: " + err.Error())
+		os.Exit(1)
+	}
+	servers := makeServersHostnameMap(serversArr)
+
+	hostServer, ok := servers[host]
+	if !ok {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error: host '" + host + "' not in Servers\n")
+		os.Exit(1)
+	}
+
+	deliveryservices, err := toc.DeliveryServicesByServer(hostServer.ID)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops Deliveryservices: " + err.Error())
+		os.Exit(1)
+	}
+
+	deliveryserviceRegexArr, err := toc.DeliveryServiceRegexes()
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops Deliveryservice Regexes: " + err.Error())
+		os.Exit(1)
+	}
+	deliveryserviceRegexes := makeDeliveryserviceRegexMap(deliveryserviceRegexArr)
+
+	cdnsArr, err := toc.CDNs()
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops CDNs: " + err.Error())
+		os.Exit(1)
+	}
+	cdns := makeCDNMap(cdnsArr)
+
+	serverParameters, err := toc.Parameters(hostServer.Profile)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting Traffic Ops Parameters for host '" + host + "' profile '" + hostServer.Profile + "': " + err.Error())
+		os.Exit(1)
+	}
+
+	parents, err := getParents(host, servers, cachegroups)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting '" + host + "' parents: " + err.Error())
+		os.Exit(1)
+	}
+
+	sameCDN := func(s tc.Server) bool {
+		return s.CDNName == hostServer.CDNName
+	}
+
+	serverAvailable := func(s tc.Server) bool {
+		status := strings.ToLower(s.Status)
+		statuses := AvailableStatuses()
+		_, ok := statuses[status]
+		return ok
+	}
+
+	parents = filterParents(parents, sameCDN)
+	parents = filterParents(parents, serverAvailable)
+
+	cdnSSLKeys, err := toc.CDNSSLKeys(hostServer.CDNName)
+	if err != nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error getting '" + hostServer.CDNName + "' SSL keys: " + err.Error())
+		os.Exit(1)
+	}
+	dsCerts := makeDSCertMap(cdnSSLKeys)
+
+	return createRulesOld(host, deliveryservices, parents, deliveryserviceRegexes, cdns, serverParameters, dsCerts, certDir)
+}
+
+// func createRulesNewAPI(toc *to.Session, host string, certDir string) (remap.RemapRules, error) {
+// 	cacheCfg, err := toc.CacheConfig(host)
+// 	if err != nil {
+// 		fmt.Printf("Error getting Traffic Ops Cache Config: %v\n", err)
+// 		os.Exit(1)
+// 	}
+
+// 	rules := []remapdata.RemapRule{}
+
+// 	allowedIPs, err := makeAllowIP(cacheCfg.AllowIP)
+// 	if err != nil {
+// 		return remap.RemapRules{}, fmt.Errorf("creating allowed IPs: %v", err)
+// 	}
+
+// 	cdnSSLKeys, err := toc.CDNSSLKeys(cacheCfg.CDN)
+// 	if err != nil {
+// 		fmt.Printf("Error getting %v SSL keys: %v\n", cacheCfg.CDN, err)
+// 		os.Exit(1)
+// 	}
+// 	dsCerts := makeDSCertMap(cdnSSLKeys)
+
+// 	weight := DefaultRuleWeight
+// 	retryNum := DefaultRetryNum
+// 	timeout := DefaultTimeout
+// 	parentSelection := DefaultRuleParentSelection
+
+// 	for _, ds := range cacheCfg.DeliveryServices {
+// 		protocol := ds.Protocol
+// 		queryStringRule, err := getQueryStringRule(ds.QueryStringIgnore)
+// 		if err != nil {
+// 			return remap.RemapRules{}, fmt.Errorf("getting deliveryservice %v Query String Rule: %v", ds.XMLID, err)
+// 		}
+
+// 		protocolStrs := []ProtocolStr{}
+// 		switch protocol {
+// 		case ProtocolHTTP:
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "http"})
+// 		case ProtocolHTTPS:
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+// 		case ProtocolHTTPAndHTTPS:
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "http"})
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+// 		case ProtocolHTTPToHTTPS:
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "https"})
+// 			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+// 		}
+
+// 		cert, hasCert := dsCerts[ds.XMLID]
+// 		// DEBUG
+// 		// if protocol != ProtocolHTTP {
+// 		// 	if !hasCert {
+// 		// 		fmt.Fprint(os.Stderr, "HTTPS delivery service: "+ds.XMLID+" has no certificate!\n")
+// 		// 	} else if err := createCertificateFiles(cert, certDir); err != nil {
+// 		// 		fmt.Fprint(os.Stderr, "HTTPS delivery service "+ds.XMLID+" failed to create certificate: "+err.Error()+"\n")
+// 		// 	}
+// 		// }
+
+// 		dsType := strings.ToLower(ds.Type)
+// 		if !strings.HasPrefix(dsType, "http") && !strings.HasPrefix(dsType, "dns") {
+// 			fmt.Printf("createRules skipping deliveryservice %v - unknown type %v", ds.XMLID, ds.Type)
+// 			continue
+// 		}
+
+// 		for _, protocolStr := range protocolStrs {
+// 			for _, dsRegex := range ds.Regexes {
+// 				rule := remapdata.RemapRule{}
+// 				pattern, patternLiteralRegex := trimLiteralRegex(dsRegex)
+// 				rule.Name = fmt.Sprintf("%s.%s.%s.%s", ds.XMLID, protocolStr.From, protocolStr.To, pattern)
+// 				rule.From = buildFrom(protocolStr.From, pattern, patternLiteralRegex, host, dsType, cacheCfg.Domain)
+
+// 				if protocolStr.From == "https" && hasCert {
+// 					rule.CertificateFile = getCertFileName(cert, certDir)
+// 					rule.CertificateKeyFile = getCertKeyFileName(cert, certDir)
+// 					// fmt.Fprintf(os.Stderr, "HTTPS delivery service: "+ds.XMLID+" certificate %+v\n", cert)
+// 				}
+
+// 				for _, parent := range cacheCfg.Parents {
+// 					to, proxyURLStr := buildToNew(parent, protocolStr.To, ds.OriginFQDN, dsType)
+// 					proxyURL, err := url.Parse(proxyURLStr)
+// 					if err != nil {
+// 						return remap.RemapRules{}, fmt.Errorf("error parsing deliveryservice %v parent %v proxy_url: %v", ds.XMLID, parent.Host, proxyURLStr)
+// 					}
+
+// 					ruleTo := remapdata.RemapRuleTo{
+// 						RemapRuleToBase: remapdata.RemapRuleToBase{
+// 							URL:      to,
+// 							Weight:   &weight,
+// 							RetryNum: &retryNum,
+// 						},
+// 						ProxyURL:   proxyURL,
+// 						RetryCodes: DefaultRetryCodes(),
+// 						Timeout:    &timeout,
+// 					}
+// 					rule.To = append(rule.To, ruleTo)
+// 					// TODO get from TO?
+// 					rule.RetryNum = &retryNum
+// 					rule.Timeout = &timeout
+// 					rule.RetryCodes = DefaultRetryCodes()
+// 					rule.QueryString = queryStringRule
+// 					rule.DSCP = ds.DSCP
+// 					if err != nil {
+// 						return remap.RemapRules{}, err
+// 					}
+// 					rule.ConnectionClose = DefaultRuleConnectionClose
+// 					rule.ParentSelection = &parentSelection
+// 				}
+// 				rules = append(rules, rule)
+// 			}
+// 		}
+// 	}
+
+// 	remapRules := remap.RemapRules{
+// 		Rules:           rules,
+// 		RetryCodes:      DefaultRetryCodes(),
+// 		Timeout:         &timeout,
+// 		ParentSelection: &parentSelection,
+// 		Stats:           remap.RemapRulesStats{Allow: allowedIPs},
+// 	}
+
+// 	return remapRules, nil
+// }
+
+func makeServersHostnameMap(servers []tc.Server) map[string]tc.Server {
+	m := map[string]tc.Server{}
+	for _, server := range servers {
+		m[server.HostName] = server
+	}
+	return m
+}
+
+func makeCachegroupsNameMap(cgs []tcv13.CacheGroup) map[string]tcv13.CacheGroup {
+	m := map[string]tcv13.CacheGroup{}
+	for _, cg := range cgs {
+		m[cg.Name] = cg
+	}
+	return m
+}
+
+func makeDeliveryservicesXMLIDMap(dses []tc.DeliveryService) map[string]tc.DeliveryService {
+	m := map[string]tc.DeliveryService{}
+	for _, ds := range dses {
+		m[ds.XMLID] = ds
+	}
+	return m
+}
+
+func makeDeliveryservicesIDMap(dses []tc.DeliveryService) map[int]tc.DeliveryService {
+	m := map[int]tc.DeliveryService{}
+	for _, ds := range dses {
+		m[ds.ID] = ds
+	}
+	return m
+}
+
+func makeDeliveryserviceRegexMap(dsrs []tc.DeliveryServiceRegexes) map[string][]tc.DeliveryServiceRegex {
+	m := map[string][]tc.DeliveryServiceRegex{}
+	for _, dsr := range dsrs {
+		m[dsr.DSName] = dsr.Regexes
+	}
+	return m
+}
+
+func makeCDNMap(cdns []tcv13.CDN) map[string]tcv13.CDN {
+	m := map[string]tcv13.CDN{}
+	for _, cdn := range cdns {
+		m[cdn.Name] = cdn
+	}
+	return m
+}
+
+func makeDSCertMap(sslKeys []tcv13.CDNSSLKeys) map[string]tcv13.CDNSSLKeys {
+	m := map[string]tcv13.CDNSSLKeys{}
+	for _, sslkey := range sslKeys {
+		m[sslkey.DeliveryService] = sslkey
+	}
+	return m
+}
+
+func getServerDeliveryservices(hostname string, servers map[string]tc.Server, dssrvs []tc.DeliveryServiceServer, dses []tc.DeliveryService) ([]tc.DeliveryService, error) {
+	server, ok := servers[hostname]
+	if !ok {
+		return nil, fmt.Errorf("server %v not found in Traffic Ops Servers", hostname)
+	}
+	serverID := server.ID
+	dsByID := makeDeliveryservicesIDMap(dses)
+	serverDses := []tc.DeliveryService{}
+	for _, dssrv := range dssrvs {
+		if dssrv.Server != serverID {
+			continue
+		}
+		ds, ok := dsByID[dssrv.DeliveryService]
+		if !ok {
+			return nil, fmt.Errorf("delivery service ID %v not found in Traffic Ops DeliveryServices", dssrv.DeliveryService)
+		}
+		serverDses = append(serverDses, ds)
+	}
+	return serverDses, nil
+}
+
+func getParents(hostname string, servers map[string]tc.Server, cachegroups map[string]tcv13.CacheGroup) ([]tc.Server, error) {
+	server, ok := servers[hostname]
+	if !ok {
+		return nil, fmt.Errorf("hostname not found in Servers")
+	}
+
+	cachegroup, ok := cachegroups[server.Cachegroup]
+	if !ok {
+		return nil, fmt.Errorf("server cachegroup '%v' not found in Cachegroups", server.Cachegroup)
+	}
+
+	parents := []tc.Server{}
+	for _, server := range servers {
+		if server.Cachegroup == cachegroup.ParentName {
+			parents = append(parents, server)
+		}
+	}
+	return parents, nil
+}
+
+func filterParents(parents []tc.Server, include func(tc.Server) bool) []tc.Server {
+	newParents := []tc.Server{}
+	for _, parent := range parents {
+		if include(parent) {
+			newParents = append(newParents, parent)
+		}
+	}
+	return newParents
+}
+
+const ProtocolHTTP = 0
+const ProtocolHTTPS = 1
+const ProtocolHTTPAndHTTPS = 2
+const ProtocolHTTPToHTTPS = 3
+
+type ProtocolStr struct {
+	From string
+	To   string
+}
+
+// trimLiteralRegex removes the prefix and suffix in .*\.foo\.* delivery service regexes. Traffic Ops Delivery Services have regexes of this form, which aren't really regexes, and the .*\ and \.* need stripped to construct the "to" FQDN. Returns the trimmed string, and whether it was of the form `.*\.foo\.*`
+func trimLiteralRegex(s string) (string, bool) {
+	prefix := `.*\.`
+	suffix := `\..*`
+	if strings.HasPrefix(s, prefix) && strings.HasSuffix(s, suffix) {
+		return s[len(prefix) : len(s)-len(suffix)], true
+	}
+	return s, false
+}
+
+// buildFrom builds the remap "from" URI prefix. It assumes ttype is a delivery service type HTTP or DNS, behavior is undefined for any other ttype.
+func buildFrom(protocol string, pattern string, patternLiteralRegex bool, host string, dsType string, cdnDomain string) string {
+	if !patternLiteralRegex {
+		return protocol + "://" + pattern
+	}
+
+	if isHTTP := strings.HasPrefix(dsType, "http"); isHTTP {
+		return protocol + "://" + host + "." + pattern + "." + cdnDomain
+	}
+
+	return protocol + "://" + "edge." + pattern + "." + cdnDomain
+}
+
+func dsTypeSkipsMid(ttype string) bool {
+	ttype = strings.ToLower(ttype)
+	if ttype == "http_no_cache" || ttype == "http_live" || ttype == "dns_live" {
+		return true
+	}
+	if strings.Contains(ttype, "live") && !strings.Contains(ttype, "natnl") {
+		return true
+	}
+	return false
+}
+
+// buildTo returns the to URL, and the Proxy URL (if any)
+func buildTo(parentServer tc.Server, protocol string, originURI string, dsType string) (string, string) {
+	// TODO add port?
+	to := originURI
+	proxy := ""
+	if !dsTypeSkipsMid(dsType) {
+		proxy = "http://" + parentServer.HostName + "." + parentServer.DomainName + ":" + strconv.Itoa(parentServer.TCPPort)
+	}
+	return to, proxy
+}
+
+// // buildToNew returns the to URL, and the Proxy URL (if any)
+// func buildToNew(parent tc.CacheConfigParent, protocol string, originURI string, dsType string) (string, string) {
+// 	// TODO add port?
+// 	to := originURI
+// 	proxy := ""
+// 	if !dsTypeSkipsMid(dsType) {
+// 		proxy = "http://" + parent.Host + "." + parent.Domain + ":" + strconv.FormatUint(uint64(parent.Port), 10)
+// 	}
+// 	return to, proxy
+// }
+
+const DeliveryServiceQueryStringCacheAndRemap = 0
+const DeliveryServiceQueryStringNoCacheRemap = 1
+const DeliveryServiceQueryStringNoCacheNoRemap = 2
+
+func getQueryStringRule(dsQstringIgnore int) (remapdata.QueryStringRule, error) {
+	switch dsQstringIgnore {
+	case DeliveryServiceQueryStringCacheAndRemap:
+		return remapdata.QueryStringRule{Remap: true, Cache: true}, nil
+	case DeliveryServiceQueryStringNoCacheRemap:
+		return remapdata.QueryStringRule{Remap: true, Cache: true}, nil
+	case DeliveryServiceQueryStringNoCacheNoRemap:
+		return remapdata.QueryStringRule{Remap: false, Cache: false}, nil
+	default:
+		return remapdata.QueryStringRule{}, fmt.Errorf("unknown delivery service qstringIgnore value '%v'", dsQstringIgnore)
+	}
+}
+
+func DefaultRetryCodes() map[int]struct{} {
+	return map[int]struct{}{}
+}
+
+const DefaultRuleWeight = 1.0
+const DefaultRetryNum = 5
+const DefaultTimeout = time.Millisecond * 5000
+const DefaultRuleConnectionClose = false
+const DefaultRuleParentSelection = remapdata.ParentSelectionTypeConsistentHash
+
+func getAllowIP(params []tc.Parameter) ([]*net.IPNet, error) {
+	ips := []string{}
+	for _, param := range params {
+		if (param.Name == "allow_ip" || param.Name == "allow_ip6") && param.ConfigFile == "astats.config" {
+			ips = append(ips, strings.Split(param.Value, ",")...)
+		}
+	}
+	return makeAllowIP(ips)
+}
+
+func makeAllowIP(ips []string) ([]*net.IPNet, error) {
+	cidrs := make([]*net.IPNet, len(ips))
+	for i, ip := range ips {
+		ip = strings.TrimSpace(ip)
+		if !strings.Contains(ip, "/") {
+			if strings.Contains(ip, ":") {
+				ip += "/128"
+			} else {
+				ip += "/32"
+			}
+		}
+		_, cidrnet, err := net.ParseCIDR(ip)
+		if err != nil {
+			return nil, fmt.Errorf("error parsing CIDR '%s': %v", ip, err)
+		}
+		cidrs[i] = cidrnet
+	}
+	return cidrs, nil
+}
+
+func createRulesOld(
+	hostname string,
+	dses []tc.DeliveryService,
+	parents []tc.Server,
+	dsRegexes map[string][]tc.DeliveryServiceRegex,
+	cdns map[string]tcv13.CDN,
+	hostParams []tc.Parameter,
+	dsCerts map[string]tcv13.CDNSSLKeys,
+	certDir string,
+) (remap.RemapRules, error) {
+	rules := []remapdata.RemapRule{}
+	allowedIPs, err := getAllowIP(hostParams)
+	if err != nil {
+		return remap.RemapRules{}, fmt.Errorf("getting allowed IPs: %v", err)
+	}
+
+	weight := DefaultRuleWeight
+	retryNum := DefaultRetryNum
+	timeout := DefaultTimeout
+	parentSelection := DefaultRuleParentSelection
+
+	for _, ds := range dses {
+		protocol := ds.Protocol
+		queryStringRule, err := getQueryStringRule(ds.QStringIgnore)
+		if err != nil {
+			return remap.RemapRules{}, fmt.Errorf("getting deliveryservice %v Query String Rule: %v", ds.XMLID, err)
+		}
+
+		cdn, ok := cdns[ds.CDNName]
+		if !ok {
+			return remap.RemapRules{}, fmt.Errorf("deliveryservice '%v' CDN '%v' not found", ds.XMLID, ds.CDNName)
+		}
+
+		protocolStrs := []ProtocolStr{}
+		switch protocol {
+		case ProtocolHTTP:
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "http"})
+		case ProtocolHTTPS:
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+		case ProtocolHTTPAndHTTPS:
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "http"})
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+		case ProtocolHTTPToHTTPS:
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "http", To: "https"})
+			protocolStrs = append(protocolStrs, ProtocolStr{From: "https", To: "https"})
+		}
+
+		cert, hasCert := dsCerts[ds.XMLID]
+		if protocol != ProtocolHTTP {
+			if !hasCert {
+				fmt.Fprint(os.Stderr, time.Now().Format(time.RFC3339Nano)+" HTTPS delivery service: "+ds.XMLID+" has no certificate!\n")
+			} else if err := createCertificateFiles(cert, certDir); err != nil {
+				fmt.Fprint(os.Stderr, time.Now().Format(time.RFC3339Nano)+" HTTPS delivery service "+ds.XMLID+" failed to create certificate: "+err.Error()+"\n")
+			}
+		}
+
+		dsType := strings.ToLower(ds.Type)
+		if !strings.HasPrefix(dsType, "http") && !strings.HasPrefix(dsType, "dns") {
+			fmt.Printf(time.Now().Format(time.RFC3339Nano)+" createRules skipping deliveryservice %v - unknown type %v", ds.XMLID, ds.Type)
+			continue
+		}
+
+		toClientHeaders, toOriginHeaders, err := makeModHdrs(ds.EdgeHeaderRewrite, ds.RemapText)
+		if err != nil {
+			return remap.RemapRules{}, err
+		}
+		acl, err := makeACL(ds.RemapText)
+		if err != nil {
+			fmt.Println(time.Now().Format(time.RFC3339Nano) + " createRules skipping deliveryservice '" + ds.XMLID + "' - unsupported ACL " + ds.RemapText)
+			continue
+		}
+
+		for _, protocolStr := range protocolStrs {
+			regexes, ok := dsRegexes[ds.XMLID]
+			if !ok {
+				return remap.RemapRules{}, fmt.Errorf("deliveryservice '%v' has no regexes", ds.XMLID)
+			}
+
+			for _, dsRegex := range regexes {
+				rule := remapdata.RemapRule{}
+				pattern, patternLiteralRegex := trimLiteralRegex(dsRegex.Pattern)
+				rule.Name = fmt.Sprintf("%s.%s.%s.%s", ds.XMLID, protocolStr.From, protocolStr.To, pattern)
+				rule.From = buildFrom(protocolStr.From, pattern, patternLiteralRegex, hostname, dsType, cdn.DomainName)
+
+				if protocolStr.From == "https" && hasCert {
+					rule.CertificateFile = getCertFileName(cert, certDir)
+					rule.CertificateKeyFile = getCertKeyFileName(cert, certDir)
+					// fmt.Fprintf(os.Stderr, "HTTPS delivery service: "+ds.XMLID+" certificate %+v\n", cert)
+				}
+
+				rule.PluginsShared = map[string]json.RawMessage{}
+				for _, parent := range parents {
+					to, proxyURLStr := buildTo(parent, protocolStr.To, ds.OrgServerFQDN, dsType)
+					proxyURL, err := url.Parse(proxyURLStr)
+					if err != nil {
+						return remap.RemapRules{}, fmt.Errorf("error parsing deliveryservice %v parent %v proxy_url: %v", ds.XMLID, parent.HostName, proxyURLStr)
+					}
+
+					ruleTo := remapdata.RemapRuleTo{
+						RemapRuleToBase: remapdata.RemapRuleToBase{
+							URL:      to,
+							Weight:   &weight,
+							RetryNum: &retryNum,
+						},
+						ProxyURL:   proxyURL,
+						RetryCodes: DefaultRetryCodes(),
+						Timeout:    &timeout,
+					}
+					rule.To = append(rule.To, ruleTo)
+					// TODO get from TO?
+					rule.RetryNum = &retryNum
+					rule.Timeout = &timeout
+					rule.RetryCodes = DefaultRetryCodes()
+					rule.QueryString = queryStringRule
+					rule.DSCP = ds.DSCP
+					rule.ConnectionClose = DefaultRuleConnectionClose
+					rule.ParentSelection = &parentSelection
+					rule.Allow = acl
+					rule.Plugins = map[string]interface{}{}
+					rule.Plugins["modify_headers"] = toClientHeaders
+					rule.Plugins["modify_parent_request_headers"] = toOriginHeaders
+					remapTextJSON, err := json.Marshal(ds.RemapText)
+					if err != nil {
+						return remap.RemapRules{}, fmt.Errorf("parsing deliveryservice '%v' remap text '%v' marshalling JSON: %v", ds.XMLID, ds.RemapText, err)
+					}
+					rule.PluginsShared[web.RemapTextKey] = remapTextJSON
+				}
+				rules = append(rules, rule)
+			}
+		}
+	}
+
+	globalPlugins := map[string]interface{}{}
+	serverHeader := web.Hdr{Name: "Server", Value: "Grove/0.33"}
+	setHeaders := []web.Hdr{}
+	setHeaders = append(setHeaders, serverHeader)
+	globalHeaders := web.ModHdrs{Set: setHeaders}
+	globalPlugins["modify_response_headers_global"] = globalHeaders
+	remapRules := remap.RemapRules{
+		Rules:           rules,
+		RetryCodes:      DefaultRetryCodes(),
+		Timeout:         &timeout,
+		ParentSelection: &parentSelection,
+		Stats:           remapdata.RemapRulesStats{Allow: allowedIPs},
+		Plugins:         globalPlugins,
+	}
+
+	return remapRules, nil
+}
+
+func getCertFileName(cert tcv13.CDNSSLKeys, dir string) string {
+	return dir + string(os.PathSeparator) + strings.Replace(cert.Hostname, "*.", "", -1) + ".crt"
+}
+
+func getCertKeyFileName(cert tcv13.CDNSSLKeys, dir string) string {
+	return dir + string(os.PathSeparator) + strings.Replace(cert.Hostname, "*.", "", -1) + ".key"
+}
+
+func createCertificateFiles(cert tcv13.CDNSSLKeys, dir string) error {
+	certFileName := getCertFileName(cert, dir)
+	crt, err := base64.StdEncoding.DecodeString(cert.Certificate.Crt)
+	if err != nil {
+		return errors.New("base64decoding certificate file " + certFileName + ": " + err.Error())
+	}
+	if err := ioutil.WriteFile(certFileName, crt, 0644); err != nil {
+		return errors.New("writing certificate file " + certFileName + ": " + err.Error())
+	}
+
+	keyFileName := getCertKeyFileName(cert, dir)
+	key, err := base64.StdEncoding.DecodeString(cert.Certificate.Key)
+	if err != nil {
+		return errors.New("base64decoding certificate key " + keyFileName + ": " + err.Error())
+	}
+	if err := ioutil.WriteFile(keyFileName, key, 0644); err != nil {
+		return errors.New("writing certificate key file " + keyFileName + ": " + err.Error())
+	}
+	return nil
+}
+
+// makeACL is a hack to take the very ATS/TrafficControl remap_text field ACLs, and turn them into grove ACLs
+// note that the astats ACL input already has CIDR notation, but the DS ACL input is IP ranges.
+func makeACL(remapTxt string) ([]*net.IPNet, error) {
+	allow := []*net.IPNet{}
+	remapTxt = strings.Join(strings.Fields(remapTxt), " ")
+	// We only have @action=allow not @action=deny, and only @scr_ip= not @in_op=
+	// so only worrying about that here.
+	if strings.HasPrefix(remapTxt, "@action=allow") {
+		remaps := strings.Split(remapTxt, " ")
+		if len(remaps) < 2 {
+			return nil, errors.New("malformed remapTxt '" + remapTxt + "'")
+		}
+		for _, allowStr := range remaps[1:] {
+			allBits := 32
+			if strings.Contains(allowStr, ":") {
+				allBits = 128 // not sure if v6 works, only tested with our v4 ACLs.
+			}
+			if strings.Contains(allowStr, "-") {
+				a := strings.Split(strings.TrimPrefix(allowStr, "@src_ip="), "-")
+				if len(a) < 2 {
+					return nil, errors.New("malformed remapTxt '" + remapTxt + "'")
+				}
+				startAddrStr := a[0]
+				endAddrStr := a[1]
+				start := net.ParseIP(startAddrStr)
+				end := net.ParseIP(endAddrStr)
+				if start == nil || end == nil {
+					// This error catches all unexpected (but valid) options.
+					return nil, fmt.Errorf("error parsing allow string: %v, %v", allowStr, remapTxt)
+				}
+				maskBits := allBits
+				mask := net.CIDRMask(maskBits, allBits)
+				for !start.Mask(mask).Equal(end.Mask(mask)) {
+					maskBits--
+					mask = net.CIDRMask(maskBits, allBits)
+				}
+				fmt.Println(time.Now().Format(time.RFC3339Nano)+" DEBUG base: ", startAddrStr, " end:", endAddrStr, " maskBits:", maskBits) // TODO remove?
+				allow = append(allow, &net.IPNet{IP: start.Mask(mask), Mask: mask})
+			} else {
+				addrStr := strings.Trim(allowStr, "@src_ip=")
+				addr := net.ParseIP(addrStr)
+				if addr == nil {
+					// This error catches all unexpected (but valid) options.
+					return nil, fmt.Errorf("error parsing allow string: %v, %v", allowStr, remapTxt)
+				}
+				mask := net.CIDRMask(allBits, allBits)
+				allow = append(allow, &net.IPNet{IP: addr.Mask(mask), Mask: mask})
+			}
+		}
+	}
+	return allow, nil
+}
+
+// makeModHdrs is a pretty nasty hack to take the very ATS/TrafficControl specific config stuff from Traffic Ops and turn it into header manipulation rules for grove.
+// Returns the client header modifications, the origin header modifications, and any error.
+func makeModHdrs(edgeHRW string, remapTXT string) (web.ModHdrs, web.ModHdrs, error) {
+
+	if edgeHRW == "" && remapTXT == "" {
+		return web.ModHdrs{}, web.ModHdrs{}, nil
+	}
+
+	// Normalize the whitespaces to just a single " "
+	edgeHRW = strings.Join(strings.Fields(edgeHRW), " ")
+	remapTXT = strings.Join(strings.Fields(remapTXT), " ")
+
+	toClientList := web.ModHdrs{}
+	toOriginList := web.ModHdrs{}
+	if strings.Contains(edgeHRW, "-header") {
+		toOrigin := true
+		for _, line := range strings.Split(edgeHRW, "__RETURN__") {
+			line = strings.TrimSuffix(line, "[L]")
+			parts := strings.Fields(line)
+			if len(parts) < 2 {
+				return web.ModHdrs{}, web.ModHdrs{}, errors.New("malformed line '" + line + "'")
+			}
+			switch {
+			case parts[0] == "cond":
+				if parts[1] == "%{SEND_RESPONSE_HDR_HOOK}" {
+					toOrigin = false
+				}
+				if parts[1] == "%{SEND_REQUEST_HDR_HOOK}" {
+					toOrigin = true
+				}
+			case parts[0] == "set-header" || parts[0] == "add-header": // Technically these are different
+				if len(parts) < 3 {
+					return web.ModHdrs{}, web.ModHdrs{}, errors.New("malformed line '" + line + "'")
+				}
+				hdr := web.Hdr{Name: parts[1], Value: strings.Join(parts[2:], " ")}
+				if toOrigin {
+					toOriginList.Set = append(toOriginList.Set, hdr)
+				} else {
+					toClientList.Set = append(toClientList.Set, hdr)
+				}
+			case parts[0] == "rm-header":
+				if toOrigin {
+					toOriginList.Drop = append(toOriginList.Drop, parts[1])
+				} else {
+					toClientList.Drop = append(toClientList.Drop, parts[1])
+				}
+			}
+		}
+	}
+
+	return toClientList, toOriginList, nil
+}
diff --git a/grove/icache/icache.go b/grove/icache/icache.go
new file mode 100644
index 000000000..8a82dd1ad
--- /dev/null
+++ b/grove/icache/icache.go
@@ -0,0 +1,31 @@
+package icache
+
+/*
+   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.
+*/
+
+import (
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+)
+
+// TODO change to return errors
+
+type Cache interface {
+	Add(key string, val *cacheobj.CacheObj) bool
+	Capacity() uint64
+	Get(key string) (*cacheobj.CacheObj, bool)
+	Peek(key string) (*cacheobj.CacheObj, bool)
+	Keys() []string
+	Size() uint64
+	Close()
+}
diff --git a/grove/lru/lru.go b/grove/lru/lru.go
new file mode 100644
index 000000000..9c8d0c0d2
--- /dev/null
+++ b/grove/lru/lru.go
@@ -0,0 +1,76 @@
+package lru
+
+/*
+   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.
+*/
+
+import (
+	"container/list"
+	"sync"
+)
+
+type LRU struct {
+	l      *list.List
+	lElems map[string]*list.Element
+	m      sync.RWMutex
+}
+
+type listObj struct {
+	key  string
+	size uint64
+}
+
+func NewLRU() *LRU {
+	return &LRU{l: list.New(), lElems: map[string]*list.Element{}}
+}
+
+// Add adds the key to the LRU, with the given size. Returns the size of the the old size, or 0 if no key existed.
+func (c *LRU) Add(key string, size uint64) uint64 {
+	c.m.Lock()
+	defer c.m.Unlock()
+	if elem, ok := c.lElems[key]; ok {
+		c.l.MoveToFront(elem)
+		oldSize := elem.Value.(*listObj).size
+		elem.Value.(*listObj).size = size
+		return oldSize
+	}
+	c.lElems[key] = c.l.PushFront(&listObj{key, size})
+	return 0
+}
+
+// RemoveOldest returns the key, size, and true if the LRU is nonempty; else false.
+func (c *LRU) RemoveOldest() (string, uint64, bool) {
+	c.m.Lock()
+	defer c.m.Unlock()
+
+	elem := c.l.Back()
+	if elem == nil {
+		return "", 0, false
+	}
+	c.l.Remove(elem)
+	obj := elem.Value.(*listObj)
+	delete(c.lElems, obj.key)
+	return obj.key, obj.size, true
+}
+
+// Keys returns a string array of the keys
+func (c *LRU) Keys() []string {
+	c.m.RLock()
+	defer c.m.RUnlock()
+	arr := make([]string, 0)
+	for e := c.l.Back(); e != nil; e = e.Prev() {
+		object := e.Value.(*listObj)
+		arr = append(arr, object.key)
+	}
+	return arr
+}
diff --git a/grove/memcache/memcache.go b/grove/memcache/memcache.go
new file mode 100644
index 000000000..2cd29ce58
--- /dev/null
+++ b/grove/memcache/memcache.go
@@ -0,0 +1,129 @@
+package memcache
+
+/*
+   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.
+*/
+
+import (
+	"sync"
+	"sync/atomic"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/lru"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+// MemCache is a threadsafe memory cache with a soft byte limit, enforced via LRU.
+type MemCache struct {
+	lru          *lru.LRU                      // threadsafe.
+	cache        map[string]*cacheobj.CacheObj // mutexed: MUST NOT access without locking cacheM. TODO test performance of sync.Map
+	cacheM       sync.RWMutex                  // TODO test performance of one mutex for lru+cache
+	sizeBytes    uint64                        // atomic: MUST NOT access without sync.atomic
+	maxSizeBytes uint64                        // constant: MUST NOT be modified after creation
+	gcChan       chan<- uint64
+}
+
+func New(bytes uint64) *MemCache {
+	log.Errorf("MemCache.New: creating cache with %d capacity.", bytes)
+	gcChan := make(chan uint64, 1)
+	c := &MemCache{
+		lru:          lru.NewLRU(),
+		cache:        map[string]*cacheobj.CacheObj{},
+		maxSizeBytes: bytes,
+		gcChan:       gcChan,
+	}
+	go c.gcManager(gcChan)
+	return c
+}
+
+func (c *MemCache) Get(key string) (*cacheobj.CacheObj, bool) {
+	c.cacheM.RLock()
+	obj, ok := c.cache[key]
+	if ok {
+		c.lru.Add(key, obj.Size) // TODO directly call c.ll.MoveToFront
+	}
+	c.cacheM.RUnlock()
+	return obj, ok
+}
+
+func (c *MemCache) Peek(key string) (*cacheobj.CacheObj, bool) {
+	c.cacheM.RLock()
+	obj, ok := c.cache[key]
+	c.cacheM.RUnlock()
+	return obj, ok
+}
+
+func (c *MemCache) Add(key string, val *cacheobj.CacheObj) bool {
+	c.cacheM.Lock()
+	c.cache[key] = val
+	c.cacheM.Unlock()
+	oldSize := c.lru.Add(key, val.Size)
+	sizeChange := val.Size - oldSize
+	if sizeChange == 0 {
+		return false
+	}
+	newSizeBytes := atomic.AddUint64(&c.sizeBytes, sizeChange)
+	if newSizeBytes <= c.maxSizeBytes {
+		return false
+	}
+	c.doGC(newSizeBytes)
+	return false // TODO remove eviction from interface; it's unnecessary and expensive
+}
+
+func (c *MemCache) Size() uint64 { return atomic.LoadUint64(&c.sizeBytes) }
+func (c *MemCache) Close()       {}
+
+// doGC kicks off garbage collection if it isn't already. Does not block.
+func (c *MemCache) doGC(cacheSizeBytes uint64) {
+	select {
+	case c.gcChan <- cacheSizeBytes:
+	default: // don't block if GC is already running
+	}
+}
+
+// gcManager is the garbage collection manager function, designed to be run in a goroutine. Never returns.
+func (c *MemCache) gcManager(gcChan <-chan uint64) {
+	for cacheSizeBytes := range gcChan {
+		c.gc(cacheSizeBytes)
+	}
+}
+
+// gc executes garbage collection, until the cache size is under the max. This should be called in a singleton manager goroutine, so only one goroutine is ever doing garbage collection at any time.
+func (c *MemCache) gc(cacheSizeBytes uint64) {
+	for cacheSizeBytes > c.maxSizeBytes {
+		log.Debugf("MemCache.gc cacheSizeBytes %+v > c.maxSizeBytes %+v\n", cacheSizeBytes, c.maxSizeBytes)
+		key, sizeBytes, exists := c.lru.RemoveOldest() // TODO change lru to use strings
+		if !exists {
+			// should never happen
+			log.Errorf("MemCache.gc sizeBytes %v > %v maxSizeBytes, but LRU is empty!? Setting cache size to 0!\n", cacheSizeBytes, c.maxSizeBytes)
+			atomic.StoreUint64(&c.sizeBytes, 0)
+			return
+		}
+
+		log.Debugf("MemCache.gc deleting key '" + key + "'")
+		c.cacheM.Lock()
+		delete(c.cache, key)
+		c.cacheM.Unlock()
+
+		cacheSizeBytes = atomic.AddUint64(&c.sizeBytes, ^uint64(sizeBytes-1)) // subtract sizeBytes
+	}
+}
+
+func (c *MemCache) Keys() []string {
+	return c.lru.Keys()
+}
+
+func (c *MemCache) Capacity() uint64 {
+	return c.maxSizeBytes
+}
diff --git a/grove/plugin/README.md b/grove/plugin/README.md
new file mode 100644
index 000000000..8dec9be29
--- /dev/null
+++ b/grove/plugin/README.md
@@ -0,0 +1,149 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you 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.
+-->
+
+# Adding a Plugin
+
+To add a plugin, create a new `.go` file in the `grove/plugin` directory. This file should have a unique name, to avoid conflicts. Consider prefixing it with your company name, website, or a UUID.
+
+The filename, sans `.go`, is the name of your plugin, and will be the key used for configuration in the remap file. For example, if your file is `f49e54fc-fd17-4e1c-92c6-67028fde8504-hello-world.go`, the name of your plugin is `f49e54fc-fd17-4e1c-92c6-67028fde8504-hello-world`.
+
+Plugins are registered via calls to `AddPlugin` inside an `init` function in the plugin's file.
+
+The `Funcs` object contains functions for each hook, as well as a load function for loading configuration from the remap file. The current hooks are `startup`, `onRequest`, `beforeParentRequest`, `beforeRespond`, and `afterRespond`. If your plugin does not use a hook, it may be nil.
+
+* `startup` is called when the application starts. Examples are set global data, or start a global goroutine needed by the plugin.
+
+* `onRequest` is called immediately when a request is received. It returns a boolean indicating whether to stop processing. Examples are IP blocking, or serving custom endpoints for statistics or to invalidate a cache entry.
+
+* `beforeParentRequest` is called immediately before making a request to a parent. It may manipulate the request being made to the parent. Examples are removing headers in the client request such as `Range`.
+
+* `beforeRespond` is called immediately before responding to a client. It may manipulate the code, headers, and body being returned. Examples are header modifications, or handling if-modified-since requests.
+
+* `afterRespond` is called immediately after responding to the client. Examples are recording stats, or writing to an access log.
+
+* `load` is not a hook, but rather a function to load arbitrary data from the remap config file. It is given a `json.RawMessage`, and can return any object. The object it returns is then passed to this plugin's hooks.
+
+The simplest example is the `hello_world` plugin. See `grove/plugin/hello_world.go`.
+
+```go
+func init() {
+	AddPlugin(10000, Funcs{startup: hello})
+}
+
+func hello(icfg interface{}, d StartupData) {
+	log.Errorf("Hello World! I'm a startup plugin! We're starting with %v bytes!\n", d.Config.CacheSizeBytes)
+}
+```
+
+The plugin is initialized via `AddPlugin`, and its `hello` function is set as the `startup` hook. The `hello` function has the signature of `plugin.StartupHook`.
+
+To pass data from one hook in your plugin to a hook that's called later, set the `Context` member of the `Data` object. For an example, see `hello_context.go`:
+
+```go
+func init() {
+	AddPlugin(10000, Funcs{startup: helloCtxStart, afterRespond: helloCtxAfterResp})
+}
+
+func helloCtxStart(icfg interface{}, d StartupData) {
+	*d.Context = 42
+	log.Debugf("Hello World! Start set context: %+v\n", d.Context)
+}
+
+func helloCtxAfterResp(icfg interface{}, d AfterRespondData) {
+	ictx := d.Context
+	ctx, ok := (*ictx).(int)
+	log.Debugf("Hello World! After Response got context: %+v %+v\n", ok, ctx)
+}
+```
+
+The `startup` hook function `helloCtxStartup` sets the context pointer to the value `42`, and then the same plugin's `afterRespond` hook `helloCtxAfterResp` retrieves the value from its Data `.Context` pointer.
+
+For an example of configuration, see `modify_headers.go`.
+
+```go
+func init() {
+	AddPlugin(10000, Funcs{load: modRespHdrLoad, beforeRespond: modRespHdr})
+}
+
+type Hdr struct {
+	Name  string `json:"name"`
+	Value string `json:"value"`
+}
+
+type ModHdrs struct {
+	Set  []Hdr    `json:"set"`
+	Drop []string `json:"drop"`
+}
+
+func modRespHdrLoad(b json.RawMessage) interface{} {
+	cfg := ModHdrs{}
+	err := json.Unmarshal(b, &cfg)
+	if err != nil {
+		log.Errorln("modifyheaders loading config, unmarshalling JSON: " + err.Error())
+		return nil
+	}
+	log.Debugf("modifyheaders load success: %+v\n", cfg)
+	return &cfg
+}
+
+func modRespHdr(icfg interface{}, d BeforeRespondData) {
+	if icfg == nil {
+		log.Debugln("modifyheaders has no config, returning.")
+		return
+	}
+	cfg, ok := icfg.(*ModHdrs)
+	if !ok {
+		// should never happen
+		log.Errorf("modifyheaders config '%v' type '%T' expected *ModHdrs\n", icfg, icfg)
+		return
+	}
+...
+}
+```
+
+The load function `modRespHdrLoad` unmarshals the given `json.RawMessage` into its expected type, and returns a pointer to the object. The beforeRespond hook function `modRespHdr` then casts the interface it's given to the type its load function returned.
+
+Load functions are given configuration objects from the remap file, for the rule being processed, under the key `plugins`. Recall the name of the plugin is the filename, with `.go` removed. For example, for the `modify_headers.go` plugin:
+
+```
+{
+  "rules": [
+    {
+      "name": "my-remap-rule",
+      "plugins": {
+        "modify_headers": {
+          "set": [{"name": "Server", "value": "grove42"}],
+          "drop": ["X-Powered-By"]
+        }
+      },
+  ...
+```
+
+If a given rule does not have a plugin key, the global object will be used, as with other remap fields. For example:
+
+```
+{
+  "plugins": {
+    "modify_headers": {
+    "set": [{"name": "Server", "value": "grove42"}],
+    "drop": ["X-Powered-By"]
+  },
+  "rules": [
+  ...
+```
diff --git a/grove/plugin/README_http_cacheinspector.md b/grove/plugin/README_http_cacheinspector.md
new file mode 100644
index 000000000..e008e573b
--- /dev/null
+++ b/grove/plugin/README_http_cacheinspector.md
@@ -0,0 +1,87 @@
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you 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.
+-->
+
+# Cache Inspector Plugin
+
+The cache inspector plugin allows you to view the contents of the cache in a browser.  Point your browser at `http://<yourcacheiporhostname:yourcacheport>/_cacheinspect` to get started. Access to this endpoint is limited to the IP ranges defined in the `stats` object of the global configuration.
+
+Example output:
+
+```
+Jump to:  disk  my-disk-cache-two  
+
+
+*** Cache "" ***
+
+  * Size of in use cache:      9.5M 
+  * Cache capacity:            9.5M 
+  * Number of elements in LRU: 169
+  * Objects in cache sorted by Least Recently Used on top, showing only first 100 and last 100:
+
+     #		Code	Size	        Age			            Key
+     00000	200	    34K	            16h19m9.135951506s  	GET:http://localhost/34k.bin?hah
+     00001	200	    35K	            16h19m9.103181146s  	GET:http://localhost/35k.bin?hah
+     00002	200	    36K	            16h19m9.079490592s  	GET:http://localhost/36k.bin?hah
+     00003	200	    37K	            16h19m9.050852429s  	GET:http://localhost/37k.bin?hah
+     00004	200	    38K	            16h19m9.020264008s  	GET:http://localhost/38k.bin?hah
+     00005	200	    39K	            16h19m8.989722029s  	GET:http://localhost/39k.bin?hah
+     00006	200     40K	            16h19m8.967823063s  	GET:http://localhost/40k.bin?hah
+     00007	200	    41K	            16h19m8.939422783s  	GET:http://localhost/41k.bin?hah
+     00008	200	    42K	            16h19m8.913485123s  	GET:http://localhost/42k.bin?h
+```
+
+
+Any of the keys can be clicked to peek at the details of this object in cache, and this will not update the LRU list:
+
+```
+Key: GET:http://localhost/34k.bin?hah cache: ""
+
+  > User-Agent: curl/7.54.0
+  > Accept: */*
+  > Host: localhost
+
+  < Last-Modified: Sun, 01 Apr 2018 19:42:43 GMT
+  < Etag: "8800-568cead43b2c0"
+  < Accept-Ranges: bytes
+  < Content-Length: 34816
+  < Content-Type: application/octet-stream
+  < Date: Sat, 14 Apr 2018 22:18:35 GMT
+  < Server: Apache/2.4.29 (Unix)
+
+  Code:                         200
+  OriginCode:                   200
+  ProxyURL:                     
+  ReqTime:                      2018-04-14 16:18:35.098419 -0600 MDT m=+33.256292902
+  ReqRespTime:                  2018-04-14 16:18:35.098843 -0600 MDT m=+33.256716928
+  RespRespTime:                 2018-04-14 22:18:35 +0000 GMT
+  LastModified:                 2018-04-01 19:42:43 +0000 GMT
+```
+
+The following querystrings can be used: 
+
+- `cache=<cachename>`
+Only display the contents of the cache `<cachename>`. Use `cache=` (empty cachename) for the default memory cachename `""`.
+- `head=<number>`
+Number of items to list from the top of the top of the LRU. Default is 100.
+- `key=<keystring>`
+Show details page of the given key.
+- `search=<searchstring>`
+List only items that have `<searchstring>` in the key. This overrules `<head>` and `<tail>`, when search is used these are ignored. 
+- `tail=<number>`
+Number of items to list from the bottom of the top of the LRU. Default is 100.
diff --git a/grove/plugin/ats_log.go b/grove/plugin/ats_log.go
new file mode 100644
index 000000000..3b885f326
--- /dev/null
+++ b/grove/plugin/ats_log.go
@@ -0,0 +1,144 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+const NSPerSec = 1000000000
+
+func init() {
+	AddPlugin(20000, Funcs{afterRespond: atsLog})
+}
+
+func atsLog(icfg interface{}, d AfterRespondData) {
+	now := time.Now()
+	bytesSent := web.TryGetBytesWritten(d.W, d.Conn, d.BytesWritten)
+
+	proxyHierarchyStr, proxyNameStr := getParentStrings(d.RespCode, d.CacheHit, d.ProxyStr, d.ToFQDN)
+
+	log.EventRaw(atsEventLogStr(
+		now,
+		d.ClientIP,
+		d.Hostname,
+		d.Req.Host,
+		d.Port,
+		d.ToFQDN,
+		d.Scheme,
+		d.Req.URL.String(),
+		d.Req.Method,
+		d.Req.Proto,
+		d.RespCode,
+		now.Sub(d.ReqTime),
+		bytesSent,
+		d.OriginCode,
+		d.OriginBytes,
+		d.RespSuccess,
+		d.OriginReqSuccess,
+		getCacheHitStr(d.CacheHit, d.OriginConnectFailed),
+		proxyHierarchyStr,
+		proxyNameStr,
+		d.Req.UserAgent(),
+		d.Req.Header.Get("X-Money-Trace"),
+		d.RequestID,
+	))
+}
+
+// getParentStrings returns the phr and pqsn ATS log event strings (in that order).
+// This covers almost all occurences that we currently see from ATS.
+func getParentStrings(code int, hit bool, proxyStr string, toFQDN string) (string, string) {
+	// the most common case (hopefully), do this first
+	if hit {
+		return "NONE", "-"
+	}
+	if code >= 200 {
+		if proxyStr != "" {
+			return "PARENT_HIT", strings.Split(proxyStr, ":")[0]
+		}
+		return "DIRECT", toFQDN
+	}
+	return "EMPTY", "-"
+}
+
+// getCacheHitStr returns the event log string for whether the request was a cache hit. For a request not in the cache, pass `ReuseCannot` to indicate a cache miss.
+func getCacheHitStr(hit bool, originConnectFailed bool) string {
+	if originConnectFailed {
+		return "ERR_CONNECT_FAIL"
+	}
+	if hit {
+		return "TCP_HIT"
+	}
+	return "TCP_MISS"
+}
+
+func atsEventLogStr(
+	timestamp time.Time, // (prefix)
+	clientIP string, // chi
+	selfHostname string,
+	reqHost string, // phn
+	reqPort string, // php
+	originHost string, // shn
+	scheme string, // url
+	url string, // url
+	method string, // cqhm
+	protocol string, // cqhv
+	respCode int, // pssc
+	timeToServe time.Duration, // ttms
+	bytesSent uint64, // b
+	originStatus int, // sssc
+	originBytes uint64, // sscl
+	clientRespSuccess bool, // cfsc
+	originReqSuccess bool, // pfsc
+	cacheHit string, // crc
+	proxyUsed string, // phr
+	thisProxyName string, // pqsn
+	clientUserAgent string, // client user agent
+	xmt string, // moneytrace header
+	requestID uint64, // Grove tracing ID - not part of real ATS log format
+) string {
+	unixNano := timestamp.UnixNano()
+	unixSec := unixNano / NSPerSec
+	unixFrac := 1 / (unixNano % NSPerSec)
+	unixFracStr := strconv.FormatInt(unixFrac, 10)
+	if len(unixFracStr) > 3 {
+		unixFracStr = unixFracStr[:3]
+	}
+	cfsc := "FIN"
+	if !clientRespSuccess {
+		cfsc = "INTR"
+	}
+	pfsc := "FIN"
+	if !originReqSuccess {
+		pfsc = "INTR"
+	}
+
+	// TODO escape quotes within useragent, moneytrace
+	clientUserAgent = `"` + clientUserAgent + `"`
+	if xmt == "" {
+		xmt = `"-"`
+	} else {
+		xmt = `"` + xmt + `"`
+	}
+
+	// 	1505408269.011 chi=2001:beef:cafe:f::2 phn=cdn-ec-nyc-001-01.nyc.kabletown.net php=80 shn=disc-org.kabletown.net url=http://edge.disc.kabletown.net/250001/3306/lb.xml cqhm=GET cqhv=HTTP/1.1 pssc=200 ttms=0 b=1778 sssc=000 sscl=0 cfsc=FIN pfsc=FIN crc=TCP_MEM_HIT phr=NONE pqsn=- uas="Go-http-client/1.1" xmt="-"
+	return strconv.FormatInt(unixSec, 10) + "." + unixFracStr + " chi=" + clientIP + " phn=" + selfHostname + " php=" + reqPort + " shn=" + originHost + " url=" + scheme + "://" + reqHost + url + " cqhn=" + method + " cqhv=" + protocol + " pssc=" + strconv.FormatInt(int64(respCode), 10) + " ttms=" + strconv.FormatInt(int64(timeToServe/time.Millisecond), 10) + " b=" + strconv.FormatInt(int64(bytesSent), 10) + " sssc=" + strconv.FormatInt(int64(originStatus), 10) + " sscl=" + strconv.FormatInt(int64(originBytes), 10) + " cfsc=" + cfsc + " pfsc=" + pfsc + " crc=" + cacheHit + " phr=" + proxyUsed + " pqsn=" + thisProxyName + " uas=" + clientUserAgent + " xmt=" + xmt + " reqid=" + strconv.FormatUint(requestID, 10) + "\n"
+}
diff --git a/grove/plugin/hello_context.go b/grove/plugin/hello_context.go
new file mode 100644
index 000000000..eb162233c
--- /dev/null
+++ b/grove/plugin/hello_context.go
@@ -0,0 +1,33 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	// AddPlugin(10000, Funcs{startup: helloCtxStart, afterRespond: helloCtxAfterResp})
+}
+
+func helloCtxStart(icfg interface{}, d StartupData) {
+	*d.Context = 42
+	log.Debugf("Hello World! Start set context: %+v\n", *d.Context)
+}
+
+func helloCtxAfterResp(icfg interface{}, d AfterRespondData) {
+	ctx, ok := (*d.Context).(int)
+	log.Debugf("Hello World! After Response got context: %+v %+v\n", ok, ctx)
+}
diff --git a/grove/plugin/hello_world.go b/grove/plugin/hello_world.go
new file mode 100644
index 000000000..9682a0866
--- /dev/null
+++ b/grove/plugin/hello_world.go
@@ -0,0 +1,27 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	// AddPlugin(10000, Funcs{startup: hello})
+}
+
+func hello(icfg interface{}, d StartupData) {
+	log.Errorf("Hello World! I'm a startup plugin! We're starting with %v bytes!\n", d.Config.CacheSizeBytes)
+}
diff --git a/grove/plugin/http_cacheinspector.go b/grove/plugin/http_cacheinspector.go
new file mode 100644
index 000000000..23b40d199
--- /dev/null
+++ b/grove/plugin/http_cacheinspector.go
@@ -0,0 +1,194 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"fmt"
+	"net/http"
+	"net/url"
+	"sort"
+	"strconv"
+	"strings"
+
+	"code.cloudfoundry.org/bytefmt"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{onRequest: cacheinspect})
+}
+
+// CacheStatsEndpoint is our reserved path
+const CacheStatsEndpoint = "/_cacheinspect"
+
+func writeHTMLPageHeader(w http.ResponseWriter) {
+	w.Header().Set("Content-Type", "text/html")
+	w.Write([]byte(`
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Grove Cache Inspector</title>
+</head>
+<body>
+<pre>
+`))
+
+}
+
+func writeHTMLPageFooter(w http.ResponseWriter) {
+	w.Write([]byte(`
+</pre>
+</body>
+</html>
+`))
+}
+
+func cacheinspect(icfg interface{}, d OnRequestData) bool {
+	if !strings.HasPrefix(d.R.URL.Path, CacheStatsEndpoint) {
+		log.Debugf("plugin onrequest http_cacheinspect returning, not in path '" + d.R.URL.Path + "'\n")
+		return false
+	}
+
+	log.Debugf("plugin onrequest http_cacheinspect calling\n")
+
+	reqTime := time.Now()
+	w := d.W
+	req := d.R
+
+	// TODO access log? Stats byte count?
+	ip, err := web.GetIP(req)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Errorln("statHandler ServeHTTP failed to get IP: " + ip.String())
+		return true
+	}
+	if !d.StatRules.Allowed(ip) {
+		code := http.StatusForbidden
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Debugln("statHandler.ServeHTTP IP " + ip.String() + " FORBIDDEN") // TODO event?
+		return true
+	}
+
+	respCode := http.StatusOK
+	w.WriteHeader(respCode)
+	writeHTMLPageHeader(w)
+	qstringOptions := req.URL.Query()
+
+	// The default cache = "", which is the default memcache
+	cacheToDisplay := ""
+	showSelectCache := false
+	if cNameArr, cNamePresent := qstringOptions["cache"]; cNamePresent {
+		showSelectCache = true
+		cacheToDisplay = cNameArr[0]
+	}
+	if keyArr, showKey := qstringOptions["key"]; showKey {
+		hLine := fmt.Sprintf("Key: %s cache: \"%s\"\n\n", keyArr[0], cacheToDisplay)
+		w.Write([]byte(hLine))
+		if cacheObject, ok := d.Stats.CachePeek(keyArr[0], cacheToDisplay); ok {
+			for k, v := range cacheObject.ReqHeaders {
+				w.Write([]byte(fmt.Sprintf("  > %s: %s\n", k, strings.Join(v, ","))))
+			}
+			w.Write([]byte("\n"))
+			for k, v := range cacheObject.RespHeaders {
+				w.Write([]byte(fmt.Sprintf("  < %s: %s\n", k, strings.Join(v, ","))))
+			}
+			w.Write([]byte("\n"))
+			w.Write([]byte(fmt.Sprintf("  Code:                         %d\n", cacheObject.Code)))
+			w.Write([]byte(fmt.Sprintf("  OriginCode:                   %d\n", cacheObject.OriginCode)))
+			w.Write([]byte(fmt.Sprintf("  ProxyURL:                     %s\n", cacheObject.ProxyURL)))
+			w.Write([]byte(fmt.Sprintf("  ReqTime:                      %v\n", cacheObject.ReqTime)))
+			w.Write([]byte(fmt.Sprintf("  ReqRespTime:                  %v\n", cacheObject.ReqRespTime)))
+			w.Write([]byte(fmt.Sprintf("  RespRespTime:                 %v\n", cacheObject.RespRespTime)))
+			w.Write([]byte(fmt.Sprintf("  LastModified:                 %v\n", cacheObject.LastModified)))
+		} else {
+			w.Write([]byte("Not Found"))
+		}
+	} else {
+		searchArr, doSearch := qstringOptions["search"]
+		cacheNames := d.Stats.CacheNames()
+		sort.Strings(cacheNames)
+		w.Write([]byte(fmt.Sprintf("Jump to:")))
+		for _, cName := range cacheNames {
+			w.Write([]byte(fmt.Sprintf("<a href=#%s>%s</a>  ", cName, cName)))
+		}
+		w.Write([]byte(fmt.Sprintf("\n")))
+		for _, cName := range cacheNames {
+			if showSelectCache && cName != cacheToDisplay {
+				continue
+			}
+			w.Write([]byte(fmt.Sprintf("<a name=%s></a>", cName)))
+			w.Write([]byte(fmt.Sprintf("\n\n<b>*** Cache \"%s\" ***</b>\n", cName)))
+			keys := d.Stats.CacheKeys(cName)
+			size, _ := d.Stats.CacheSizeByName(cName)
+			capacity, _ := d.Stats.CacheCapacityByName(cName)
+			w.Write([]byte(fmt.Sprintf("\n  * Size of in use cache:      %s \n", bytefmt.ByteSize(size))))
+			w.Write([]byte(fmt.Sprintf("  * Cache capacity:            %s \n", bytefmt.ByteSize(capacity))))
+			w.Write([]byte(fmt.Sprintf("  * Number of elements in LRU: %d\n", len(keys))))
+			// tail is how much from the top of the LRU to display, top of the LRU is most recently used. head is the other side.
+			head := 100
+			tail := 100
+			tailStr, ok := qstringOptions["tail"]
+			if ok {
+				tail, err = strconv.Atoi(tailStr[0])
+				if err != nil {
+					log.Errorf("Error converting tail value to int: %v", err)
+				}
+			}
+			headStr, ok := qstringOptions["head"]
+			if ok {
+				head, err = strconv.Atoi(headStr[0])
+				if err != nil {
+					log.Errorf("Error converting head value to int: %v", err)
+					head = 100
+				}
+			}
+
+			w.Write([]byte(fmt.Sprintf("  * Objects in cache sorted by Least Recently Used on top, ")))
+			if doSearch {
+				w.Write([]byte(fmt.Sprintf("showing only strings matching %s:\n", searchArr[0])))
+			} else {
+				w.Write([]byte(fmt.Sprintf("showing only first %d and last %d:\n\n", head, tail)))
+			}
+
+			w.Write([]byte(fmt.Sprintf("<b>     #\t\tCode\tSize\tAge\t\t\tKey</b>\n")))
+			for i, key := range keys {
+				if (doSearch && !strings.Contains(key, searchArr[0])) || !doSearch && (i > tail && i < len(keys)-head) {
+					continue
+				}
+
+				cacheObject, _ := d.Stats.CachePeek(key, cName)
+				age := time.Now().Sub(cacheObject.ReqRespTime)
+				w.Write([]byte(fmt.Sprintf("     %05d\t%d\t%s\t%-20v\t<a href=\"http://%s%s?key=%s&cache=%s\">%s</a>\n",
+					i, cacheObject.Code, bytefmt.ByteSize(cacheObject.Size), age, req.Host, CacheStatsEndpoint, url.QueryEscape(key), cName, key)))
+			}
+
+		}
+	}
+
+	writeHTMLPageFooter(w)
+	clientIP, _ := web.GetClientIPPort(req)
+	now := time.Now()
+	// TODO add eventId?
+	log.EventRaw(atsEventLogStr(now, clientIP, d.Hostname, req.Host, d.Port, "-", d.Scheme, req.URL.String(), req.Method, req.Proto, respCode, now.Sub(reqTime), 0, 0, 0, true, true, getCacheHitStr(true, false), "-", "-", req.UserAgent(), req.Header.Get("X-Money-Trace"), 1))
+
+	return true
+}
diff --git a/grove/plugin/http_callgc.go b/grove/plugin/http_callgc.go
new file mode 100644
index 000000000..992513b2e
--- /dev/null
+++ b/grove/plugin/http_callgc.go
@@ -0,0 +1,74 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"runtime"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{onRequest: callgc})
+}
+
+const CallGCEndpoint = "/_callgc"
+
+func callgc(icfg interface{}, d OnRequestData) bool {
+	if !strings.HasPrefix(d.R.URL.Path, CallGCEndpoint) {
+		return false
+	}
+	reqTime := time.Now()
+
+	log.Debugf("plugin onrequest http_callgc calling\n")
+
+	w := d.W
+	req := d.R
+
+	// TODO access log? Stats byte count?
+	ip, err := web.GetIP(req)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Errorln("statHandler ServeHTTP failed to get IP: " + ip.String())
+		return true
+	}
+	if !d.StatRules.Allowed(ip) {
+		code := http.StatusForbidden
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Debugln("statHandler.ServeHTTP IP " + ip.String() + " FORBIDDEN") // TODO event?
+		return true
+	}
+
+	runtime.GC()
+
+	respCode := http.StatusNoContent
+	w.WriteHeader(respCode)
+
+	clientIP, _ := web.GetClientIPPort(req)
+
+	now := time.Now()
+	// log, so we know if someone is hitting this endpoint when they shouldn't be. GC is expensive, this could become an accidental DDOS.
+	log.EventRaw(atsEventLogStr(now, clientIP, d.Hostname, req.Host, d.Port, "-", d.Scheme, req.URL.String(), req.Method, req.Proto, respCode, now.Sub(reqTime), 0, 0, 0, true, true, getCacheHitStr(true, false), "-", "-", req.UserAgent(), req.Header.Get("X-Money-Trace"), d.RequestID))
+
+	return true
+}
diff --git a/grove/plugin/http_memstats.go b/grove/plugin/http_memstats.go
new file mode 100644
index 000000000..7a35a4749
--- /dev/null
+++ b/grove/plugin/http_memstats.go
@@ -0,0 +1,77 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+	"net/http"
+	"runtime"
+	"strings"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{onRequest: memstats})
+}
+
+const MemStatsEndpoint = "/_memstats"
+
+func memstats(icfg interface{}, d OnRequestData) bool {
+	if !strings.HasPrefix(d.R.URL.Path, MemStatsEndpoint) {
+		log.Debugf("plugin onrequest http_memstats returning, not in path '" + d.R.URL.Path + "'\n")
+		return false
+	}
+
+	log.Debugf("plugin onrequest http_memstats calling\n")
+
+	w := d.W
+	req := d.R
+
+	// TODO access log? Stats byte count?
+	ip, err := web.GetIP(req)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Errorln("statHandler ServeHTTP failed to get IP: " + ip.String())
+		return true
+	}
+	if !d.StatRules.Allowed(ip) {
+		code := http.StatusForbidden
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Debugln("statHandler.ServeHTTP IP " + ip.String() + " FORBIDDEN") // TODO event?
+		return true
+	}
+
+	// TODO gzip
+	// TODO cache for 1 second
+
+	stats := runtime.MemStats{}
+	runtime.ReadMemStats(&stats)
+
+	bytes, err := json.Marshal(stats)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+	}
+	w.Header().Set("Content-Type", "application/json")
+	w.Write(bytes)
+	return true
+}
diff --git a/grove/plugin/http_stats.go b/grove/plugin/http_stats.go
new file mode 100644
index 000000000..8958696e0
--- /dev/null
+++ b/grove/plugin/http_stats.go
@@ -0,0 +1,169 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"bufio"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"os"
+	"strconv"
+	"strings"
+	"unicode"
+
+	"github.com/apache/incubator-trafficcontrol/grove/stat"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{onRequest: stats})
+}
+
+const StatsEndpoint = "/_astats"
+
+func stats(icfg interface{}, d OnRequestData) bool {
+	if !strings.HasPrefix(d.R.URL.Path, StatsEndpoint) {
+		log.Debugf("plugin onrequest http_stats returning, not in path '" + d.R.URL.Path + "'\n")
+		return false
+	}
+
+	log.Debugf("plugin onrequest http_stats calling\n")
+
+	w := d.W
+	req := d.R
+
+	// TODO access log? Stats byte count?
+	ip, err := web.GetIP(req)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Errorln("statHandler ServeHTTP failed to get IP: " + ip.String())
+		return true
+	}
+	if !d.StatRules.Allowed(ip) {
+		code := http.StatusForbidden
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+		log.Debugln("statHandler.ServeHTTP IP " + ip.String() + " FORBIDDEN") // TODO event?
+		return true
+	}
+
+	// TODO gzip
+	system := LoadSystemStats(d.Stats, d.InterfaceName) // TODO goroutine on a timer?
+	ats := map[string]interface{}{"server": "6.2.1"}
+	if req.URL.Query().Get("application") != "system" {
+		ats = LoadRemapStats(d.Stats, d.HTTPConns, d.HTTPSConns)
+	}
+	stats := stat.StatsJSON{System: system, ATS: ats}
+
+	bytes, err := json.Marshal(stats)
+	if err != nil {
+		code := http.StatusInternalServerError
+		w.WriteHeader(code)
+		w.Write([]byte(http.StatusText(code)))
+	}
+	w.Header().Set("Content-Type", "application/json")
+	w.Write(bytes)
+	return true
+}
+
+func LoadSystemStats(stats stat.Stats, interfaceName string) stat.StatsSystemJSON {
+	s := stat.StatsSystemJSON{}
+	s.InterfaceName = interfaceName
+	s.InterfaceSpeed = loadFileAndLogInt(fmt.Sprintf("/sys/class/net/%v/speed", interfaceName))
+	s.ProcNetDev = loadFileAndLogGrep("/proc/net/dev", interfaceName)
+	s.ProcLoadAvg = loadFileAndLog("/proc/loadavg")
+	s.ConfigReloadRequests = stats.System().ConfigReloadRequests()
+	s.LastReloadRequest = stats.System().LastReloadRequest().Unix()
+	s.ConfigReloads = stats.System().ConfigReloads()
+	s.LastReload = stats.System().LastReload().Unix()
+	s.AstatsLoad = stats.System().AstatsLoad().Unix()
+	s.Something = "here" // emulate existing ATS Astats behavior
+	s.Version = stats.System().Version()
+	return s
+}
+
+func LoadRemapStats(stats stat.Stats, httpConns *web.ConnMap, httpsConns *web.ConnMap) map[string]interface{} {
+	statsRemaps := stats.Remap()
+	rules := statsRemaps.Rules()
+	jsonStats := make(map[string]interface{}, len(rules)*8) // remap has 8 members: in, out, 2xx, 3xx, 4xx, 5xx, hits, misses
+	jsonStats["server"] = "6.2.1"                           // emulate a good ATS version
+	for _, rule := range rules {
+		ruleName := rule
+		statsRemap, ok := statsRemaps.Stats(ruleName)
+		if !ok {
+			continue // TODO warn?
+		}
+		jsonStats["plugin.remap_stats."+ruleName+".in_bytes"] = statsRemap.InBytes()
+		jsonStats["plugin.remap_stats."+ruleName+".out_bytes"] = statsRemap.OutBytes()
+		jsonStats["plugin.remap_stats."+ruleName+".status_2xx"] = statsRemap.Status2xx()
+		jsonStats["plugin.remap_stats."+ruleName+".status_3xx"] = statsRemap.Status3xx()
+		jsonStats["plugin.remap_stats."+ruleName+".status_4xx"] = statsRemap.Status4xx()
+		jsonStats["plugin.remap_stats."+ruleName+".status_5xx"] = statsRemap.Status5xx()
+		jsonStats["plugin.remap_stats."+ruleName+".cache_hits"] = statsRemap.CacheHits()
+		jsonStats["plugin.remap_stats."+ruleName+".cache_misses"] = statsRemap.CacheMisses()
+	}
+
+	jsonStats["proxy.process.http.current_client_connections"] = httpConns.Len() + httpsConns.Len()
+	jsonStats["proxy.process.http.cache_hits"] = stats.CacheHits()
+	jsonStats["proxy.process.http.cache_misses"] = stats.CacheMisses()
+	jsonStats["proxy.process.http.cache_capacity_bytes"] = stats.CacheCapacity()
+	jsonStats["proxy.process.http.cache_size_bytes"] = stats.CacheSize()
+
+	return jsonStats
+}
+
+func loadFileAndLog(filename string) string {
+	f, err := ioutil.ReadFile(filename)
+	if err != nil {
+		log.Errorf("reading system stat file %v: %v\n", filename, err)
+		return ""
+	}
+	return strings.TrimSpace(string(f))
+}
+
+func loadFileAndLogGrep(filename string, grepStr string) string {
+	file, err := os.Open(filename)
+	if err != nil {
+		log.Errorf("reading system stat file %v: %v\n", filename, err)
+		return ""
+	}
+	defer file.Close()
+
+	scanner := bufio.NewScanner(file)
+	for scanner.Scan() {
+		l := scanner.Text()
+		l = strings.TrimLeftFunc(l, unicode.IsSpace)
+		if strings.HasPrefix(l, grepStr) {
+			return l
+		}
+	}
+	log.Errorf("reading system stat file %v looking for %v: not found\n", filename, grepStr)
+	return ""
+}
+
+func loadFileAndLogInt(filename string) int64 {
+	s := loadFileAndLog(filename)
+	i, err := strconv.ParseInt(s, 10, 64)
+	if err != nil {
+		log.Errorf("parsing system stat file %v: %v\n", filename, err)
+	}
+	return i
+}
diff --git a/grove/plugin/if_modified_since.go b/grove/plugin/if_modified_since.go
new file mode 100644
index 000000000..be8ca050a
--- /dev/null
+++ b/grove/plugin/if_modified_since.go
@@ -0,0 +1,39 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+func init() {
+	AddPlugin(5000, Funcs{beforeRespond: ifModifiedSince})
+}
+
+func ifModifiedSince(icfg interface{}, d BeforeRespondData) {
+	if d.CacheObj == nil {
+		return // if we don't have a cacheobj from the origin, there's no object to have been modified.
+	}
+	modifiedSince, ok := web.GetHTTPDate(d.Req.Header, "If-Modified-Since")
+	if !ok {
+		return
+	}
+	if d.CacheObj.LastModified.After(modifiedSince) {
+		return
+	}
+	*d.Code, *d.Hdr, *d.Body = http.StatusNotModified, nil, nil
+}
diff --git a/grove/plugin/modify_headers.go b/grove/plugin/modify_headers.go
new file mode 100644
index 000000000..8146c2a9e
--- /dev/null
+++ b/grove/plugin/modify_headers.go
@@ -0,0 +1,59 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{load: modRespHdrLoad, beforeRespond: modRespHdr})
+}
+
+func modRespHdrLoad(b json.RawMessage) interface{} {
+	cfg := web.ModHdrs{}
+	err := json.Unmarshal(b, &cfg)
+	if err != nil {
+		log.Errorln("modifyheaders loading config, unmarshalling JSON: " + err.Error())
+		return nil
+	}
+	log.Debugf("modifyheaders load success: %+v\n", cfg)
+	return &cfg
+}
+
+func modRespHdr(icfg interface{}, d BeforeRespondData) {
+	log.Debugf("modifyheaders calling\n")
+	if icfg == nil {
+		log.Debugln("modifyheaders has no config, returning.")
+		return
+	}
+	cfg, ok := icfg.(*web.ModHdrs)
+	if !ok {
+		// should never happen
+		log.Errorf("modifyheaders config '%v' type '%T' expected *web.ModHdrs\n", icfg, icfg)
+		return
+	}
+
+	log.Debugf("modifyheaders config len(set) %+v len(drop) %+v\n", cfg.Set, cfg.Drop)
+	if !cfg.Any() {
+		return
+	}
+	*d.Hdr = web.CopyHeader(*d.Hdr)
+	cfg.Mod(*d.Hdr)
+}
diff --git a/grove/plugin/modify_parent_request_headers.go b/grove/plugin/modify_parent_request_headers.go
new file mode 100644
index 000000000..bcf876470
--- /dev/null
+++ b/grove/plugin/modify_parent_request_headers.go
@@ -0,0 +1,58 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{load: modOrgReqHdrLoad, beforeParentRequest: modOrgReqHdr})
+}
+
+func modOrgReqHdrLoad(b json.RawMessage) interface{} {
+	cfg := web.ModHdrs{}
+	err := json.Unmarshal(b, &cfg)
+	if err != nil {
+		log.Errorln("modify_parent_request_headers loading config, unmarshalling JSON: " + err.Error())
+		return nil
+	}
+	log.Debugf("modify_parent_request_headers load success: %+v\n", cfg)
+	return &cfg
+}
+
+func modOrgReqHdr(icfg interface{}, d BeforeParentRequestData) {
+	log.Debugf("modify_parent_request_headers calling\n")
+	if icfg == nil {
+		log.Debugln("modify_parent_request_headers has no config, returning.")
+		return
+	}
+	cfg, ok := icfg.(*web.ModHdrs)
+	if !ok {
+		// should never happen
+		log.Errorf("modify_parent_request_headers config '%v' type '%T' expected *ModHdrs\n", icfg, icfg)
+		return
+	}
+
+	log.Debugf("modify_parent_request_headers config len(set) %+v len(drop) %+v\n", cfg.Set, cfg.Drop)
+	if !cfg.Any() {
+		return
+	}
+	cfg.Mod(d.Req.Header)
+}
diff --git a/grove/plugin/modify_response_headers_global.go b/grove/plugin/modify_response_headers_global.go
new file mode 100644
index 000000000..48de7924d
--- /dev/null
+++ b/grove/plugin/modify_response_headers_global.go
@@ -0,0 +1,59 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func init() {
+	AddPlugin(10000, Funcs{load: modRespGlblHdrLoad, beforeRespond: modRespGlblHdr})
+}
+
+func modRespGlblHdrLoad(b json.RawMessage) interface{} {
+	cfg := web.ModHdrs{}
+	err := json.Unmarshal(b, &cfg)
+	if err != nil {
+		log.Errorln("mod_response_headers_global  loading config, unmarshalling JSON: " + err.Error())
+		return nil
+	}
+	log.Debugf("mod_response_headers_global: load success: %+v\n", cfg)
+	return &cfg
+}
+
+func modRespGlblHdr(icfg interface{}, d BeforeRespondData) {
+	log.Debugf("mod_response_headers_global calling\n")
+	if icfg == nil {
+		log.Debugln("mod_response_headers_global has no config, returning.")
+		return
+	}
+	cfg, ok := icfg.(*web.ModHdrs)
+	if !ok {
+		// should never happen
+		log.Errorf("mod_response_headers_global config '%v' type '%T' expected *ModGlblHdrs\n", icfg, icfg)
+		return
+	}
+
+	log.Debugf("mod_response_headers_global config len(set) %+v len(drop) %+v\n", cfg.Set, cfg.Drop)
+	if !cfg.Any() {
+		return
+	}
+	*d.Hdr = web.CopyHeader(*d.Hdr)
+	cfg.Mod(*d.Hdr)
+}
diff --git a/grove/plugin/plugin.go b/grove/plugin/plugin.go
new file mode 100644
index 000000000..ec425c7bd
--- /dev/null
+++ b/grove/plugin/plugin.go
@@ -0,0 +1,206 @@
+package plugin
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"os"
+	"path"
+	"runtime"
+	"sort"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cachedata"
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/config"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/stat"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+func AddPlugin(priority uint64, funcs Funcs) {
+	_, filename, _, ok := runtime.Caller(1)
+	if !ok {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Error plugin.AddPlugin: runtime.Caller failed, can't get plugin names") // print, because this is called in init, loggers don't exist yet
+		os.Exit(1)
+	}
+	pluginName := strings.TrimSuffix(path.Base(filename), ".go")
+	plugins = append(plugins, pluginObj{funcs: funcs, priority: priority, name: pluginName})
+}
+
+type Funcs struct {
+	load                LoadFunc
+	startup             StartupFunc
+	onRequest           OnRequestFunc
+	beforeParentRequest BeforeParentRequestFunc
+	beforeRespond       BeforeRespondFunc
+	afterRespond        AfterRespondFunc
+}
+
+type StartupData struct {
+	Config  config.Config
+	Context *interface{}
+	// Shared is the "plugins_shared" data for all rules. This is a `map[ruleName][key]value`. Keys and values are arbitrary data. This allows plugins to do pre-processing on the config, and store computed data in the context, to save processing during requests.
+	Shared map[string]map[string]json.RawMessage
+}
+
+type OnRequestData struct {
+	W             http.ResponseWriter
+	R             *http.Request
+	InterfaceName string
+	Stats         stat.Stats
+	StatRules     remapdata.RemapRulesStats
+	HTTPConns     *web.ConnMap
+	HTTPSConns    *web.ConnMap
+	RequestID     uint64
+	Context       *interface{}
+	cachedata.SrvrData
+}
+
+type BeforeParentRequestData struct {
+	Req       *http.Request
+	RemapRule string
+	Context   *interface{}
+}
+
+// BeforeRespondData holds the data passed to plugins. The objects pointed to MAY NOT be modified, however, the location pointed to may be changed for the Code, Hdr, and Body. That iss, `*d.Hdr = myHdr` is ok, but `d.Hdr.Add("a", "b") is not.
+// If that's confusing, recall `http.Header` is a map, therefore Hdr and Body are both pointers-to-pointers.
+type BeforeRespondData struct {
+	Req *http.Request
+	// CacheObj is the object to be cached, containing information about the origin request. The code, headers, and body should not be considered authoritative. Look at Code, Hdr, and Body instead, as the actual values about to be sent. Note CacheObj may be nil, if an error occurred (e.g. the Origin failed to respond).
+	CacheObj  *cacheobj.CacheObj
+	Code      *int
+	Hdr       *http.Header
+	Body      *[]byte
+	RemapRule string
+	Context   *interface{}
+}
+
+type AfterRespondData struct {
+	W         http.ResponseWriter
+	Stats     stat.Stats
+	RequestID uint64
+	cachedata.ReqData
+	cachedata.SrvrData
+	cachedata.ParentRespData
+	cachedata.RespData
+	Context *interface{}
+}
+
+type LoadFunc func(json.RawMessage) interface{}
+type StartupFunc func(icfg interface{}, d StartupData)
+type OnRequestFunc func(icfg interface{}, d OnRequestData) bool
+type BeforeParentRequestFunc func(icfg interface{}, d BeforeParentRequestData)
+type BeforeRespondFunc func(icfg interface{}, d BeforeRespondData)
+type AfterRespondFunc func(icfg interface{}, d AfterRespondData)
+
+type pluginObj struct {
+	funcs    Funcs
+	priority uint64
+	name     string
+}
+
+type pluginsSlice []pluginObj
+
+func (p pluginsSlice) Len() int           { return len(p) }
+func (p pluginsSlice) Less(i, j int) bool { return p[i].priority < p[j].priority }
+func (p pluginsSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
+
+var plugins = pluginsSlice{}
+
+func Get() Plugins {
+	sort.Sort(plugins)
+	return pluginsSlice(plugins)
+}
+
+type Plugins interface {
+	LoadFuncs() map[string]LoadFunc
+	OnStartup(cfgs map[string]interface{}, context map[string]*interface{}, d StartupData)
+	OnRequest(cfgs map[string]interface{}, context map[string]*interface{}, d OnRequestData) bool
+	OnBeforeParentRequest(cfgs map[string]interface{}, context map[string]*interface{}, d BeforeParentRequestData)
+	OnBeforeRespond(cfgs map[string]interface{}, context map[string]*interface{}, d BeforeRespondData)
+	OnAfterRespond(cfgs map[string]interface{}, context map[string]*interface{}, d AfterRespondData)
+}
+
+func (plugins pluginsSlice) LoadFuncs() map[string]LoadFunc {
+	lf := map[string]LoadFunc{}
+	for _, plugin := range plugins {
+		if plugin.funcs.load == nil {
+			continue
+		}
+		lf[plugin.name] = LoadFunc(plugin.funcs.load)
+	}
+	return lf
+}
+
+func (ps pluginsSlice) OnStartup(cfgs map[string]interface{}, context map[string]*interface{}, d StartupData) {
+	for _, p := range ps {
+		ictx := interface{}(nil)
+		context[p.name] = &ictx
+
+		if p.funcs.startup == nil {
+			continue
+		}
+		d.Context = context[p.name]
+		p.funcs.startup(cfgs[p.name], d)
+	}
+}
+
+// OnRequest returns a boolean whether to immediately stop processing the request. If a plugin returns true, this is immediately returned with no further plugins processed.
+func (ps pluginsSlice) OnRequest(cfgs map[string]interface{}, context map[string]*interface{}, d OnRequestData) bool {
+	for _, p := range ps {
+		if p.funcs.onRequest == nil {
+			continue
+		}
+		d.Context = context[p.name]
+		if stop := p.funcs.onRequest(cfgs[p.name], d); stop {
+			return true
+		}
+	}
+	return false
+}
+
+func (ps pluginsSlice) OnBeforeParentRequest(cfgs map[string]interface{}, context map[string]*interface{}, d BeforeParentRequestData) {
+	for _, p := range ps {
+		if p.funcs.beforeParentRequest == nil {
+			continue
+		}
+		d.Context = context[p.name]
+		p.funcs.beforeParentRequest(cfgs[p.name], d)
+	}
+}
+
+func (ps pluginsSlice) OnBeforeRespond(cfgs map[string]interface{}, context map[string]*interface{}, d BeforeRespondData) {
+	for _, p := range ps {
+		if p.funcs.beforeRespond == nil {
+			continue
+		}
+		d.Context = context[p.name]
+		p.funcs.beforeRespond(cfgs[p.name], d)
+	}
+}
+
+func (ps pluginsSlice) OnAfterRespond(cfgs map[string]interface{}, context map[string]*interface{}, d AfterRespondData) {
+	for _, p := range ps {
+		if p.funcs.afterRespond == nil {
+			continue
+		}
+		d.Context = context[p.name]
+		p.funcs.afterRespond(cfgs[p.name], d)
+	}
+}
diff --git a/grove/plugin/record_stats.go b/grove/plugin/record_stats.go
new file mode 100644
index 000000000..baea95621
--- /dev/null
+++ b/grove/plugin/record_stats.go
@@ -0,0 +1,23 @@
+package plugin
+
+/*
+   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.
+*/
+
+func init() {
+	AddPlugin(10000, Funcs{afterRespond: recordStats})
+}
+
+func recordStats(icfg interface{}, d AfterRespondData) {
+	d.Stats.Write(d.W, d.Conn, d.Req.Host, d.Req.RemoteAddr, d.RespCode, d.BytesWritten, d.CacheHit)
+}
diff --git a/grove/remap.json b/grove/remap.json
new file mode 100644
index 000000000..c13fb9a00
--- /dev/null
+++ b/grove/remap.json
@@ -0,0 +1,12 @@
+{
+  "rules": [
+    {
+      "from": "http://localhost:8080",
+      "to": "https://www.example.com",
+      "query-string": {
+        "remap": false,
+        "cache": false
+      }
+    }
+  ]
+}
diff --git a/grove/remap/remap.go b/grove/remap/remap.go
new file mode 100644
index 000000000..2af529ca8
--- /dev/null
+++ b/grove/remap/remap.go
@@ -0,0 +1,665 @@
+package remap
+
+/*
+   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.
+*/
+
+import (
+	"encoding/json"
+	"errors"
+	"fmt"
+	"net"
+	"net/http"
+	"net/url"
+	"os"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/chash"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+	"github.com/apache/incubator-trafficcontrol/grove/plugin"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+type HTTPRequestRemapper interface {
+	// Remap returns the remapped request, the matched rule name, whether the requestor's IP is allowed, whether to connection close, whether a match was found, and any error.
+	// Remap(r *http.Request, scheme string, failures int) Remapping
+	Rules() []remapdata.RemapRule
+	RemappingProducer(r *http.Request, scheme string) (*RemappingProducer, error)
+	StatRules() remapdata.RemapRulesStats
+	PluginCfg() map[string]interface{} // global plugins, outside the individual remap rules
+	// PluginSharedCfg returns the plugins_shared, for every remap rule. This gives plugins a chance on startup to precompute data for each remap rule, store it in the Context, and save computation during requests.
+	PluginSharedCfg() map[string]map[string]json.RawMessage
+}
+
+type simpleHTTPRequestRemapper struct {
+	remapper Remapper
+	stats    *remapdata.RemapRulesStats
+}
+
+func (hr simpleHTTPRequestRemapper) Rules() []remapdata.RemapRule         { return hr.remapper.Rules() }
+func (hr simpleHTTPRequestRemapper) StatRules() remapdata.RemapRulesStats { return *hr.stats }
+func (hr simpleHTTPRequestRemapper) PluginCfg() map[string]interface{}    { return hr.remapper.PluginCfg() }
+func (hr simpleHTTPRequestRemapper) PluginSharedCfg() map[string]map[string]json.RawMessage {
+	return hr.remapper.PluginSharedCfg()
+}
+
+// getFQDN returns the FQDN. It tries to get the FQDN from a Remap Rule. Remap Rules should always begin with the scheme, e.g. `http://`. If the given rule does not begin with a valid scheme, behavior is undefined.
+// TODO test
+func getFQDN(rule string) string {
+	schemeStr := "://"
+	schemePos := strings.Index(rule, schemeStr)
+	if schemePos == -1 {
+		return rule // invalid rule, doesn't start with a scheme
+	}
+	schemePos += len(schemeStr)
+	rule = rule[schemePos:]
+
+	slashPos := strings.Index(rule, "/")
+	if slashPos == -1 {
+		return rule // rule is just the scheme+FQDN, perfectly normal
+	}
+	rule = rule[:slashPos] // strip off the path
+	return rule
+}
+
+func NewRemappingTransport(reqTimeout time.Duration, reqKeepAlive time.Duration, reqMaxIdleConns int, reqIdleConnTimeout time.Duration) *http.Transport {
+	return &http.Transport{
+		DialContext: (&net.Dialer{
+			Timeout:   reqTimeout,
+			KeepAlive: reqKeepAlive,
+			DualStack: true,
+		}).DialContext,
+		MaxIdleConns:          reqMaxIdleConns,
+		IdleConnTimeout:       reqIdleConnTimeout,
+		TLSHandshakeTimeout:   10 * time.Second,
+		ExpectContinueTimeout: 1 * time.Second,
+		Dial: func(network, address string) (net.Conn, error) {
+			d := net.Dialer{DualStack: true, FallbackDelay: time.Millisecond * 50}
+			return d.Dial(network, address)
+		},
+	}
+}
+
+type Remapping struct {
+	Request         *http.Request
+	ProxyURL        *url.URL
+	Name            string
+	CacheKey        string
+	ConnectionClose bool
+	Timeout         time.Duration
+	RetryNum        int
+	RetryCodes      map[int]struct{}
+	Cache           icache.Cache
+	Transport       *http.Transport
+}
+
+// RemappingProducer takes an HTTP Request and returns a Remapping to be used for that request.
+// TODO rename? interface?
+type RemappingProducer struct {
+	oldURI   string
+	rule     remapdata.RemapRule
+	cacheKey string
+	failures int
+}
+
+func (p *RemappingProducer) CacheKey() string                  { return p.cacheKey }
+func (p *RemappingProducer) ConnectionClose() bool             { return p.rule.ConnectionClose }
+func (p *RemappingProducer) Name() string                      { return p.rule.Name }
+func (p *RemappingProducer) DSCP() int                         { return p.rule.DSCP }
+func (p *RemappingProducer) PluginCfg() map[string]interface{} { return p.rule.Plugins }
+func (p *RemappingProducer) Cache() icache.Cache               { return p.rule.Cache }
+func (p *RemappingProducer) FirstFQDN() string {
+	// TODO verify To is not allowed to be constructed with < 1 element
+	return strings.TrimPrefix(strings.TrimPrefix(p.rule.To[0].URL, "http://"), "https://")
+}
+func (p *RemappingProducer) ProxyStr() string {
+	if p.rule.To[0].ProxyURL != nil && p.rule.To[0].ProxyURL.Host != "" {
+		return p.rule.To[0].ProxyURL.Host
+	}
+	return "NONE" // TODO const?
+}
+
+var ErrRuleNotFound = errors.New("remap rule not found")
+var ErrIPNotAllowed = errors.New("IP not allowed")
+var ErrNoMoreRetries = errors.New("retry num exceeded")
+
+// RequestURI returns the URI of the given request. This must be used, because Go does not populate the scheme of requests that come in from clients.
+func RequestURI(r *http.Request, scheme string) string {
+	return scheme + "://" + r.Host + r.RequestURI
+}
+func (hr simpleHTTPRequestRemapper) RemappingProducer(r *http.Request, scheme string) (*RemappingProducer, error) {
+	uri := RequestURI(r, scheme)
+	rule, ok := hr.remapper.Remap(uri)
+	if !ok {
+		return nil, ErrRuleNotFound
+	}
+
+	if ip, err := web.GetIP(r); err != nil {
+		return nil, fmt.Errorf("parsing client IP: %v", err)
+	} else if !rule.Allowed(ip) {
+		return nil, ErrIPNotAllowed
+	} else {
+		log.Debugf("Allowed %v\n", ip)
+	}
+
+	cacheKey := rule.CacheKey(r.Method, uri)
+
+	return &RemappingProducer{
+		rule:     rule,
+		oldURI:   uri,
+		cacheKey: cacheKey,
+	}, nil
+}
+
+// GetNext returns the remapping to use to request, whether retries are allowed (i.e. if this is the last retry), or any error
+func (p *RemappingProducer) GetNext(r *http.Request) (Remapping, bool, error) {
+	if *p.rule.RetryNum < p.failures {
+		return Remapping{}, false, ErrNoMoreRetries
+	}
+
+	newURI, proxyURL, transport := p.rule.URI(p.oldURI, r.URL.Path, r.URL.RawQuery, p.failures)
+	p.failures++
+	newReq, err := http.NewRequest(r.Method, newURI, nil)
+	if err != nil {
+		return Remapping{}, false, fmt.Errorf("creating new request: %v\n", err)
+	}
+	web.CopyHeaderTo(r.Header, &newReq.Header)
+
+	log.Debugf("GetNext oldUri: %v, Host: %v\n", p.oldURI, newReq.Header.Get("Host"))
+	log.Debugf("GetNext newURI: %v, fqdn: %v\n", newURI, getFQDN(newURI))
+	log.Debugf("GetNext rule name: %v\n", p.rule.Name)
+
+	newReq.Header.Set("Host", getFQDN(newURI))
+
+	retryAllowed := *p.rule.RetryNum < p.failures
+	return Remapping{
+		Request:         newReq,
+		ProxyURL:        proxyURL,
+		Name:            p.rule.Name,
+		CacheKey:        p.cacheKey,
+		ConnectionClose: p.rule.ConnectionClose,
+		Timeout:         *p.rule.Timeout,
+		RetryNum:        *p.rule.RetryNum,
+		RetryCodes:      p.rule.RetryCodes,
+		Cache:           p.rule.Cache,
+		Transport:       transport,
+	}, retryAllowed, nil
+}
+
+func RemapperToHTTP(r Remapper, statRules *remapdata.RemapRulesStats) HTTPRequestRemapper {
+	return simpleHTTPRequestRemapper{remapper: r, stats: statRules}
+}
+
+func NewHTTPRequestRemapper(remap []remapdata.RemapRule, plugins map[string]interface{}, statRules *remapdata.RemapRulesStats) HTTPRequestRemapper {
+	return RemapperToHTTP(NewLiteralPrefixRemapper(remap, plugins), statRules)
+}
+
+// Remapper provides a function which takes strings and maps them to other strings. This is designed for URL prefix remapping, for a reverse proxy.
+type Remapper interface {
+	// Remap returns the given string remapped, the unique name of the rule found, and whether a remap rule was found
+	Remap(uri string) (remapdata.RemapRule, bool)
+	// Rules returns the unique names of every remap rule.
+	Rules() []remapdata.RemapRule
+	// PluginCfg returns the global plugins, outside the individual remap rules
+	PluginCfg() map[string]interface{}
+	PluginSharedCfg() map[string]map[string]json.RawMessage
+}
+
+// TODO change to use a prefix tree, for speed
+type literalPrefixRemapper struct {
+	remap   []remapdata.RemapRule
+	plugins map[string]interface{}
+}
+
+func (r literalPrefixRemapper) PluginCfg() map[string]interface{} { return r.plugins }
+
+// PluginSharedCfg returns a map of remap rule names, to a map of keys to arbitrary JSON values.
+// For example, if a JSON rule object with the name "foo" contains the key and value `"plugins_shared": {"bar": "baz"}`, the returned map will contain m["foo"]["bar"]"baz". The value may be any JSON type.
+func (r literalPrefixRemapper) PluginSharedCfg() map[string]map[string]json.RawMessage {
+	rules := r.Rules()
+	cfg := make(map[string]map[string]json.RawMessage, len(rules))
+	for _, rule := range rules {
+		cfg[rule.Name] = rule.PluginsShared
+	}
+	return cfg
+}
+
+// Remap returns the remapped string, the remap rule name, the remap rule's options, and whether a remap was found
+func (r literalPrefixRemapper) Remap(s string) (remapdata.RemapRule, bool) {
+	for _, rule := range r.remap {
+		if strings.HasPrefix(s, rule.From) {
+			return rule, true
+		}
+	}
+	return remapdata.RemapRule{}, false
+}
+
+func (r literalPrefixRemapper) Rules() []remapdata.RemapRule {
+	rules := make([]remapdata.RemapRule, len(r.remap))
+	for _, rule := range r.remap {
+		rules = append(rules, rule)
+	}
+	return rules
+}
+
+func NewLiteralPrefixRemapper(remap []remapdata.RemapRule, plugins map[string]interface{}) Remapper {
+	return literalPrefixRemapper{remap: remap, plugins: plugins}
+}
+
+type RemapRulesStatsJSON struct {
+	Allow []string `json:"allow"`
+	Deny  []string `json:"deny"`
+}
+
+type RemapRulesBase struct {
+	RetryNum      *int                       `json:"retry_num"`
+	PluginsShared map[string]json.RawMessage `json:"plugins_shared"`
+}
+
+type RemapRulesJSON struct {
+	RemapRulesBase
+	Rules           []RemapRuleJSON            `json:"rules"`
+	RetryCodes      *[]int                     `json:"retry_codes"`
+	TimeoutMS       *int                       `json:"timeout_ms"`
+	ParentSelection *string                    `json:"parent_selection"`
+	Stats           RemapRulesStatsJSON        `json:"stats"`
+	Plugins         map[string]json.RawMessage `json:"plugins"`
+}
+
+type RemapRules struct {
+	RemapRulesBase
+	Rules           []remapdata.RemapRule
+	RetryCodes      map[int]struct{}
+	Timeout         *time.Duration
+	ParentSelection *remapdata.ParentSelectionType
+	Stats           remapdata.RemapRulesStats
+	Plugins         map[string]interface{}
+	Cache           icache.Cache
+}
+
+type RemapRuleToJSON struct {
+	remapdata.RemapRuleToBase
+	ProxyURL   *string `json:"proxy_url"`
+	TimeoutMS  *int    `json:"timeout_ms"`
+	RetryCodes *[]int  `json:"retry_codes"`
+}
+
+type HdrModder interface {
+	Mod(h *http.Header)
+}
+
+type RemapRuleJSON struct {
+	remapdata.RemapRuleBase
+	TimeoutMS       *int                       `json:"timeout_ms"`
+	ParentSelection *string                    `json:"parent_selection"`
+	To              []RemapRuleToJSON          `json:"to"`
+	Allow           []string                   `json:"allow"`
+	Deny            []string                   `json:"deny"`
+	RetryCodes      *[]int                     `json:"retry_codes"`
+	CacheName       *string                    `json:"cache_name"`
+	Plugins         map[string]json.RawMessage `json:"plugins"`
+}
+
+// LoadRemapRules returns the loaded rules, the global plugins, the Stats remap rules, and any error
+func LoadRemapRules(path string, pluginConfigLoaders map[string]plugin.LoadFunc, caches map[string]icache.Cache, baseTransport *http.Transport) ([]remapdata.RemapRule, map[string]interface{}, *remapdata.RemapRulesStats, error) {
+	fmt.Println(time.Now().Format(time.RFC3339Nano) + " Loading Remap Rules")
+	defer func() {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Loaded Remap Rules")
+	}()
+	file, err := os.Open(path)
+	if err != nil {
+		return nil, nil, nil, err
+	}
+	defer file.Close()
+
+	remapRulesJSON := RemapRulesJSON{}
+	if err := json.NewDecoder(file).Decode(&remapRulesJSON); err != nil {
+		return nil, nil, nil, fmt.Errorf("decoding JSON: %s", err)
+	}
+
+	remapRules := RemapRules{RemapRulesBase: remapRulesJSON.RemapRulesBase}
+
+	if remapRulesJSON.RetryCodes != nil {
+		remapRules.RetryCodes = make(map[int]struct{}, len(*remapRulesJSON.RetryCodes))
+		for _, code := range *remapRulesJSON.RetryCodes {
+			if _, ok := ValidHTTPCodes[code]; !ok {
+				return nil, nil, nil, fmt.Errorf("error parsing rules: retry code invalid: %v", code)
+			}
+			remapRules.RetryCodes[code] = struct{}{}
+		}
+	}
+	if remapRulesJSON.TimeoutMS != nil {
+		t := time.Duration(*remapRulesJSON.TimeoutMS) * time.Millisecond
+		if remapRules.Timeout = &t; *remapRules.Timeout < 0 {
+			return nil, nil, nil, fmt.Errorf("error parsing rules: timeout must be positive: %v", remapRules.Timeout)
+		}
+	}
+	if remapRulesJSON.ParentSelection != nil {
+		ps := remapdata.ParentSelectionTypeFromString(*remapRulesJSON.ParentSelection)
+		if remapRules.ParentSelection = &ps; *remapRules.ParentSelection == remapdata.ParentSelectionTypeInvalid {
+			return nil, nil, nil, fmt.Errorf("error parsing rules: parent selection invalid: '%v'", remapRulesJSON.ParentSelection)
+		}
+	}
+	if remapRulesJSON.Stats.Allow != nil {
+		if remapRules.Stats.Allow, err = makeIPNets(remapRulesJSON.Stats.Allow); err != nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rules allows: %v", err)
+		}
+	}
+	if remapRulesJSON.Stats.Deny != nil {
+		if remapRules.Stats.Deny, err = makeIPNets(remapRulesJSON.Stats.Deny); err != nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rules denys: %v", err)
+		}
+	}
+
+	remapRules.Plugins = make(map[string]interface{}, len(remapRulesJSON.Plugins))
+	for name, b := range remapRulesJSON.Plugins {
+		if loadF := pluginConfigLoaders[name]; loadF != nil {
+			remapRules.Plugins[name] = loadF(b)
+		}
+	}
+
+	rules := make([]remapdata.RemapRule, len(remapRulesJSON.Rules))
+	for i, jsonRule := range remapRulesJSON.Rules {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " Creating Remap Rule " + jsonRule.Name)
+		rule := remapdata.RemapRule{RemapRuleBase: jsonRule.RemapRuleBase}
+
+		rule.Plugins = make(map[string]interface{}, len(jsonRule.Plugins))
+		for name, b := range jsonRule.Plugins {
+			if loadF := pluginConfigLoaders[name]; loadF != nil {
+				rule.Plugins[name] = loadF(b)
+			}
+		}
+		for name, loader := range remapRules.Plugins {
+			if _, ok := rule.Plugins[name]; !ok {
+				rule.Plugins[name] = loader
+			}
+		}
+
+		if jsonRule.RetryCodes != nil {
+			rule.RetryCodes = make(map[int]struct{}, len(*jsonRule.RetryCodes))
+			for _, code := range *jsonRule.RetryCodes {
+				if _, ok := ValidHTTPCodes[code]; !ok {
+					return nil, nil, nil, fmt.Errorf("error parsing rule %v retry code invalid: %v", rule.Name, code)
+				}
+				rule.RetryCodes[code] = struct{}{}
+			}
+		} else {
+			rule.RetryCodes = remapRules.RetryCodes
+		}
+
+		if jsonRule.TimeoutMS != nil {
+			t := time.Duration(*jsonRule.TimeoutMS) * time.Millisecond
+			if rule.Timeout = &t; *rule.Timeout < 0 {
+				return nil, nil, nil, fmt.Errorf("error parsing rule %v timeout must be positive: %v", rule.Name, rule.Timeout)
+			}
+		} else {
+			rule.Timeout = remapRules.Timeout
+		}
+
+		if rule.RetryNum == nil {
+			rule.RetryNum = remapRules.RetryNum
+		}
+
+		if rule.PluginsShared == nil {
+			rule.PluginsShared = remapRules.PluginsShared
+		}
+
+		cacheName := "" // default string is the default cache
+		if jsonRule.CacheName != nil {
+			cacheName = *jsonRule.CacheName
+		}
+		ok := false
+		if rule.Cache, ok = caches[cacheName]; !ok {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v: cache name %v not found", rule.Name, cacheName)
+		}
+
+		if rule.Allow, err = makeIPNets(jsonRule.Allow); err != nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v allows: %v", rule.Name, err)
+		}
+		if rule.Deny, err = makeIPNets(jsonRule.Deny); err != nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v denys: %v", rule.Name, err)
+		}
+		if rule.To, err = makeTo(jsonRule.To, rule, baseTransport); err != nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v to: %v", rule.Name, err)
+		}
+		if jsonRule.ParentSelection != nil {
+			ps := remapdata.ParentSelectionTypeFromString(*jsonRule.ParentSelection)
+			if rule.ParentSelection = &ps; *rule.ParentSelection == remapdata.ParentSelectionTypeInvalid {
+				return nil, nil, nil, fmt.Errorf("error parsing rule %v parent selection invalid: '%v'", rule.Name, jsonRule.ParentSelection)
+			}
+		} else {
+			rule.ParentSelection = remapRules.ParentSelection
+		}
+
+		if rule.ParentSelection == nil {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v - no parent_selection - must be set at rules or rule level", rule.Name)
+		}
+
+		if len(rule.To) == 0 {
+			return nil, nil, nil, fmt.Errorf("error parsing rule %v - no to - must have at least one parent", rule.Name)
+		}
+
+		if *rule.ParentSelection == remapdata.ParentSelectionTypeConsistentHash {
+			rule.ConsistentHash = makeRuleHash(rule)
+		} else {
+		}
+		rules[i] = rule
+	}
+
+	return rules, remapRules.Plugins, &remapRules.Stats, nil
+}
+
+const DefaultReplicas = 1024
+
+func makeRuleHash(rule remapdata.RemapRule) chash.ATSConsistentHash {
+	h := chash.NewSimpleATSConsistentHash(DefaultReplicas)
+	for _, to := range rule.To {
+		h.Insert(&chash.ATSConsistentHashNode{Name: to.URL, ProxyURL: to.ProxyURL, Transport: to.Transport}, *to.Weight)
+	}
+	if h.First() == nil {
+		fmt.Println(time.Now().Format(time.RFC3339Nano) + " ERROR  makeRuleHash " + rule.Name + " NodeMap empty!")
+	}
+
+	return h
+}
+
+func makeTo(tosJSON []RemapRuleToJSON, rule remapdata.RemapRule, baseTransport *http.Transport) ([]remapdata.RemapRuleTo, error) {
+	tos := make([]remapdata.RemapRuleTo, len(tosJSON))
+	for i, toJSON := range tosJSON {
+		if toJSON.Weight == nil {
+			w := 1.0
+			toJSON.Weight = &w
+		}
+		to := remapdata.RemapRuleTo{RemapRuleToBase: toJSON.RemapRuleToBase}
+
+		to.Transport = baseTransport
+		if toJSON.ProxyURL != nil {
+			proxyURL, err := url.Parse(*toJSON.ProxyURL)
+			if err != nil {
+				return nil, fmt.Errorf("error parsing to %v proxy_url: %v", to.URL, toJSON.ProxyURL)
+			}
+			to.ProxyURL = proxyURL
+			newTransport := *baseTransport
+			if proxyURL != nil && proxyURL.Host != "" {
+				newTransport.Proxy = http.ProxyURL(proxyURL)
+			}
+			to.Transport = &newTransport
+		}
+
+		if toJSON.TimeoutMS != nil {
+			t := time.Duration(*toJSON.TimeoutMS) * time.Millisecond
+			if to.Timeout = &t; *to.Timeout < 0 {
+				return nil, fmt.Errorf("error parsing to %v timeout must be positive: %v", to.URL, to.Timeout)
+			}
+		} else {
+			to.Timeout = rule.Timeout
+		}
+		if toJSON.RetryCodes != nil {
+			to.RetryCodes = make(map[int]struct{}, len(*toJSON.RetryCodes))
+			for _, code := range *toJSON.RetryCodes {
+				if _, ok := ValidHTTPCodes[code]; !ok {
+					return nil, fmt.Errorf("error parsing to %v retry code invalid: %v", to.URL, code)
+				}
+				to.RetryCodes[code] = struct{}{}
+			}
+		} else {
+			to.RetryCodes = rule.RetryCodes
+		}
+		if to.RetryNum == nil {
+			to.RetryNum = rule.RetryNum
+		}
+		if to.RetryNum == nil {
+			return nil, fmt.Errorf("error parsing to %v - no retry_num - must be set at rules, rule, or to level", to.URL)
+		} else if to.Timeout == nil {
+			return nil, fmt.Errorf("error parsing to %v - no timeout_ms - must be set at rules, rule, or to level", to.URL)
+		} else if to.RetryCodes == nil {
+			return nil, fmt.Errorf("error parsing to %v - no retry_codes - must be set at rules, rule, or to level", to.URL)
+		}
+		tos[i] = to
+	}
+	return tos, nil
+}
+
+func makeIPNets(netStrs []string) ([]*net.IPNet, error) {
+	nets := make([]*net.IPNet, 0, len(netStrs))
+	for _, netStr := range netStrs {
+		netStr = strings.TrimSpace(netStr)
+		if netStr == "" {
+			continue
+		}
+		net, err := makeIPNet(netStr)
+		if err != nil {
+			return nil, fmt.Errorf("error parsing CIDR %v: %v", netStr, err)
+		}
+		nets = append(nets, net)
+	}
+	return nets, nil
+}
+
+func makeIPNet(cidr string) (*net.IPNet, error) {
+	_, cidrnet, err := net.ParseCIDR(cidr)
+	if err != nil {
+		return nil, fmt.Errorf("error parsing CIDR '%s': %v", cidr, err)
+	}
+	return cidrnet, nil
+}
+
+func LoadRemapper(path string, pluginConfigLoaders map[string]plugin.LoadFunc, caches map[string]icache.Cache, baseTransport *http.Transport) (HTTPRequestRemapper, error) {
+	rules, plugins, statRules, err := LoadRemapRules(path, pluginConfigLoaders, caches, baseTransport)
+	if err != nil {
+		return nil, err
+	}
+	return NewHTTPRequestRemapper(rules, plugins, statRules), nil
+}
+
+func RemapRulesToJSON(r RemapRules) (RemapRulesJSON, error) {
+	j := RemapRulesJSON{RemapRulesBase: r.RemapRulesBase}
+	if r.Timeout != nil {
+		i := int(0)
+		j.TimeoutMS = &i
+		*j.TimeoutMS = int(*r.Timeout / time.Millisecond)
+	}
+	if len(r.RetryCodes) > 0 {
+		rcs := []int{}
+		j.RetryCodes = &rcs
+		for code := range r.RetryCodes {
+			*j.RetryCodes = append(*j.RetryCodes, code)
+		}
+	}
+	if r.ParentSelection != nil {
+		s := ""
+		j.ParentSelection = &s
+		*j.ParentSelection = string(*r.ParentSelection)
+	}
+	for _, deny := range r.Stats.Deny {
+		j.Stats.Deny = append(j.Stats.Deny, deny.String())
+	}
+	for _, allow := range r.Stats.Allow {
+		j.Stats.Allow = append(j.Stats.Allow, allow.String())
+	}
+
+	for _, rule := range r.Rules {
+		j.Rules = append(j.Rules, buildRemapRuleToJSON(rule))
+	}
+	j.Plugins = make(map[string]json.RawMessage)
+	for name, plugin := range r.Plugins {
+		bts, err := json.Marshal(plugin)
+		if err != nil {
+			return RemapRulesJSON{}, errors.New("error marshalling plugin '" + name + "': " + err.Error())
+		}
+		j.Plugins[name] = bts
+	}
+	return j, nil
+}
+
+func buildRemapRuleToJSON(r remapdata.RemapRule) RemapRuleJSON {
+	j := RemapRuleJSON{RemapRuleBase: r.RemapRuleBase}
+	if r.Timeout != nil {
+		t := int(0)
+		j.TimeoutMS = &t
+		*j.TimeoutMS = int(*r.Timeout / time.Millisecond)
+	}
+	if r.ParentSelection != nil {
+		ps := ""
+		j.ParentSelection = &ps
+		*j.ParentSelection = string(*r.ParentSelection)
+	}
+	for _, to := range r.To {
+		j.To = append(j.To, RemapRuleToToJSON(to))
+	}
+	for _, deny := range r.Deny {
+		j.Deny = append(j.Deny, deny.String())
+	}
+	for _, allow := range r.Allow {
+		j.Allow = append(j.Allow, allow.String())
+	}
+	if r.RetryCodes != nil {
+		rc := []int{}
+		j.RetryCodes = &rc
+		for retryCode := range r.RetryCodes {
+			*j.RetryCodes = append(*j.RetryCodes, retryCode)
+		}
+	}
+	j.Plugins = make(map[string]json.RawMessage)
+	for name, plugin := range r.Plugins {
+		clientHeadersJSONBytes, _ := json.Marshal(plugin)
+		j.Plugins[name] = clientHeadersJSONBytes
+	}
+	return j
+}
+
+func RemapRuleToToJSON(r remapdata.RemapRuleTo) RemapRuleToJSON {
+	j := RemapRuleToJSON{RemapRuleToBase: r.RemapRuleToBase}
+	if r.ProxyURL != nil {
+		s := ""
+		j.ProxyURL = &s
+		*j.ProxyURL = r.ProxyURL.String()
+	}
+	if r.Timeout != nil {
+		t := int(0)
+		j.TimeoutMS = &t
+		*j.TimeoutMS = int(*r.Timeout / time.Millisecond)
+	}
+	if r.RetryCodes != nil {
+		rc := []int{}
+		j.RetryCodes = &rc
+		for retryCode := range r.RetryCodes {
+			*j.RetryCodes = append(*j.RetryCodes, retryCode)
+		}
+	}
+	return j
+}
diff --git a/grove/remap/rules.go b/grove/remap/rules.go
new file mode 100644
index 000000000..d98a04ad1
--- /dev/null
+++ b/grove/remap/rules.go
@@ -0,0 +1,510 @@
+package remap
+
+/*
+   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.
+*/
+
+import (
+	"math"
+	"net/http"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+// ValidHTTPCodes provides fast lookup whether a HTTP response code is valid per RFC7234§3
+var ValidHTTPCodes = map[int]struct{}{
+	200: {},
+	201: {},
+	202: {},
+	203: {},
+	204: {},
+	205: {},
+	206: {},
+	207: {},
+	208: {},
+	226: {},
+
+	300: {},
+	301: {},
+	302: {},
+	303: {},
+	304: {},
+	305: {},
+	306: {},
+	307: {},
+	308: {},
+
+	400: {},
+	401: {},
+	402: {},
+	403: {},
+	404: {},
+	405: {},
+	406: {},
+	407: {},
+	408: {},
+	409: {},
+	410: {},
+	411: {},
+	412: {},
+	413: {},
+	414: {},
+	415: {},
+	416: {},
+	417: {},
+	418: {},
+	421: {},
+	422: {},
+	423: {},
+	424: {},
+	428: {},
+	429: {},
+	431: {},
+	451: {},
+
+	500: {},
+	501: {},
+	502: {},
+	503: {},
+	504: {},
+	505: {},
+	506: {},
+	507: {},
+	508: {},
+	510: {},
+	511: {},
+}
+
+// cacheableResponseCodes provides fast lookup whether a HTTP response code is cacheable by default, per RFC7234§3
+var defaultCacheableResponseCodes = map[int]struct{}{
+	200: {},
+	203: {},
+	204: {},
+	206: {},
+	300: {},
+	301: {},
+	404: {},
+	405: {},
+	410: {},
+	414: {},
+	501: {},
+}
+
+// codeUnderstood returns whether the given response code is understood by this cache. Required by RFC7234§3
+func codeUnderstood(code int) bool {
+	_, ok := ValidHTTPCodes[code]
+	return ok
+}
+
+// CanCache returns whether an object can be cached per RFC 7234, based on the request headers, response headers, and response code. If strictRFC is false, this ignores request headers denying cacheability such as `no-cache`, in order to protect origins.
+// TODO add options to ignore/violate request cache-control (to protect origins)
+func CanCache(reqMethod string, reqHeaders http.Header, respCode int, respHeaders http.Header, strictRFC bool) bool {
+	log.Debugf("CanCache start\n")
+	if reqMethod != http.MethodGet {
+		return false // for now, we only support GET as a cacheable method.
+	}
+	reqCacheControl := web.ParseCacheControl(reqHeaders)
+	respCacheControl := web.ParseCacheControl(respHeaders)
+	log.Debugf("CanCache reqCacheControl %+v respCacheControl %+v\n", reqCacheControl, respCacheControl)
+	return canStoreResponse(respCode, respHeaders, reqCacheControl, respCacheControl, strictRFC) && canStoreAuthenticated(reqCacheControl, respCacheControl)
+}
+
+// CanReuseStored checks the constraints in RFC7234§4
+func CanReuseStored(reqHeaders http.Header, respHeaders http.Header, reqCacheControl web.CacheControl, respCacheControl web.CacheControl, respReqHeaders http.Header, respReqTime time.Time, respRespTime time.Time, strictRFC bool) remapdata.Reuse {
+	// TODO: remove allowed_stale, check in cache manager after revalidate fails? (since RFC7234§4.2.4 prohibits serving stale response unless disconnected).
+
+	if !selectedHeadersMatch(reqHeaders, respReqHeaders, strictRFC) {
+		log.Debugf("CanReuseStored false - selected headers don't match\n") // debug
+		return remapdata.ReuseCannot
+	}
+
+	if !fresh(respHeaders, respCacheControl, respReqTime, respRespTime) {
+		allowedStale := allowedStale(respHeaders, reqCacheControl, respCacheControl, respReqTime, respRespTime, strictRFC)
+		log.Debugf("CanReuseStored not fresh, allowed stale: %v\n", allowedStale) // debug
+		return allowedStale
+	}
+
+	if hasPragmaNoCache(reqHeaders) && strictRFC {
+		log.Debugf("CanReuseStored MustRevalidate - has pragma no-cache\n")
+		return remapdata.ReuseMustRevalidate
+	}
+
+	if _, ok := reqCacheControl["no-cache"]; ok && strictRFC {
+		log.Debugf("CanReuseStored false - request has cache-control no-cache\n")
+		return remapdata.ReuseCannot
+	}
+
+	if _, ok := respCacheControl["no-cache"]; ok {
+		log.Debugf("CanReuseStored false - response has cache-control no-cache\n")
+		return remapdata.ReuseCannot
+	}
+
+	if strictRFC && !inMinFresh(respHeaders, reqCacheControl, respCacheControl, respReqTime, respRespTime) {
+		return remapdata.ReuseMustRevalidate
+	}
+
+	log.Debugf("CanReuseStored true (respCacheControl %+v)\n", respCacheControl)
+	return remapdata.ReuseCan
+}
+
+// CanReuse is a helper wrapping CanReuseStored, returning a boolean rather than an enum, for when it's known whether MustRevalidate can be used.
+func CanReuse(reqHeader http.Header, reqCacheControl web.CacheControl, cacheObj *cacheobj.CacheObj, strictRFC bool, revalidateCanReuse bool) bool {
+	canReuse := CanReuseStored(reqHeader, cacheObj.RespHeaders, reqCacheControl, cacheObj.RespCacheControl, cacheObj.ReqHeaders, cacheObj.ReqRespTime, cacheObj.RespRespTime, strictRFC)
+	return canReuse == remapdata.ReuseCan || (canReuse == remapdata.ReuseMustRevalidate && revalidateCanReuse)
+}
+
+// canStoreAuthenticated checks the constraints in RFC7234§3.2
+// TODO: ensure RFC7234§3.2 requirements that max-age=0, must-revlaidate, s-maxage=0 are revalidated
+func canStoreAuthenticated(reqCacheControl, respCacheControl web.CacheControl) bool {
+	if _, ok := reqCacheControl["authorization"]; !ok {
+		return true
+	}
+	if _, ok := respCacheControl["must-revalidate"]; ok {
+		return true
+	}
+	if _, ok := respCacheControl["public"]; ok {
+		return true
+	}
+	if _, ok := respCacheControl["s-maxage"]; ok {
+		return true
+	}
+	log.Debugf("CanStoreAuthenticated false: has authorization, and no must-revalidate/public/s-maxage\n")
+	return false
+}
+
+// CanStoreResponse checks the constraints in RFC7234
+func canStoreResponse(
+	respCode int,
+	respHeaders http.Header,
+	reqCacheControl web.CacheControl,
+	respCacheControl web.CacheControl,
+	strictRFC bool,
+) bool {
+	if _, ok := reqCacheControl["no-store"]; strictRFC && ok {
+		log.Debugf("CanStoreResponse false: request has no-store\n")
+		return false
+	}
+	if _, ok := respCacheControl["no-store"]; ok {
+		log.Debugf("CanStoreResponse false: response has no-store\n") // RFC7234§5.2.2.3
+		return false
+	}
+	if _, ok := respCacheControl["no-cache"]; ok {
+		log.Debugf("CanStoreResponse false: response has no-cache\n") // RFC7234§5.2.2.2
+		return false
+	}
+	if _, ok := respCacheControl["private"]; ok {
+		log.Debugf("CanStoreResponse false: has private\n")
+		return false
+	}
+	if _, ok := respCacheControl["authorization"]; ok {
+		log.Debugf("CanStoreResponse false: has authorization\n")
+		return false
+	}
+	if !cacheControlAllows(respCode, respHeaders, respCacheControl) {
+		log.Debugf("CanStoreResponse false: CacheControlAllows false\n")
+		return false
+	}
+	log.Debugf("CanStoreResponse true\n")
+	return true
+}
+
+func cacheControlAllows(
+	respCode int,
+	respHeaders http.Header,
+	respCacheControl web.CacheControl,
+) bool {
+	if _, ok := respHeaders["Expires"]; ok {
+		return true
+	}
+	if _, ok := respCacheControl["max-age"]; ok {
+		return true
+	}
+	if _, ok := respCacheControl["s-maxage"]; ok {
+		return true
+	}
+	if extensionAllows() {
+		return true
+	}
+	if codeDefaultCacheable(respCode) {
+		return true
+	}
+	log.Debugf("CacheControlAllows false: no expires, no max-age, no s-max-age, no extension allows, code not default cacheable\n")
+	return false
+}
+
+// extensionAllows returns whether a cache-control extension allows the response to be cached, per RFC7234§3 and RFC7234§5.2.3.
+func extensionAllows() bool {
+	// This MUST return false unless a specific Cache Control cache-extension token exists for an extension which allows. Which is to say, returning true here without a cache-extension token is in strict violation of RFC7234.
+	// In practice, all returning true does is override whether a response code is default-cacheable. If we wanted to do that, it would be better to make codeDefaultCacheable take a strictRFC parameter.
+	return false
+}
+
+func codeDefaultCacheable(code int) bool {
+	_, ok := defaultCacheableResponseCodes[code]
+	return ok
+}
+
+// Fresh checks the constraints in RFC7234§4 via RFC7234§4.2
+func fresh(
+	respHeaders http.Header,
+	respCacheControl web.CacheControl,
+	respReqTime time.Time,
+	respRespTime time.Time,
+) bool {
+	freshnessLifetime := getFreshnessLifetime(respHeaders, respCacheControl)
+	currentAge := getCurrentAge(respHeaders, respReqTime, respRespTime)
+	log.Debugf("Fresh: freshnesslifetime %v currentAge %v\n", freshnessLifetime, currentAge)
+	fresh := freshnessLifetime > currentAge
+	return fresh
+}
+
+// GetHTTPDeltaSeconds is a helper function which gets an HTTP Delta Seconds from the given map (which is typically a `http.Header` or `CacheControl`. Returns false if the given key doesn't exist in the map, or if the value isn't a valid Delta Seconds per RFC2616§3.3.2.
+func getHTTPDeltaSeconds(m map[string][]string, key string) (time.Duration, bool) {
+	maybeSeconds, ok := m[key]
+	if !ok {
+		return 0, false
+	}
+	if len(maybeSeconds) == 0 {
+		return 0, false
+	}
+	maybeSec := maybeSeconds[0]
+
+	seconds, err := strconv.ParseUint(maybeSec, 10, 64)
+	if err != nil {
+		return 0, false
+	}
+	return time.Duration(seconds) * time.Second, true
+}
+
+// getHTTPDeltaSeconds is a helper function which gets an HTTP Delta Seconds from the given map (which is typically a `http.Header` or `CacheControl`. Returns false if the given key doesn't exist in the map, or if the value isn't a valid Delta Seconds per RFC2616§3.3.2.
+func getHTTPDeltaSecondsCacheControl(m map[string]string, key string) (time.Duration, bool) {
+	maybeSec, ok := m[key]
+	if !ok {
+		return 0, false
+	}
+	seconds, err := strconv.ParseUint(maybeSec, 10, 64)
+	if err != nil {
+		return 0, false
+	}
+	return time.Duration(seconds) * time.Second, true
+}
+
+// getFreshnessLifetime calculates the freshness_lifetime per RFC7234§4.2.1
+func getFreshnessLifetime(respHeaders http.Header, respCacheControl web.CacheControl) time.Duration {
+	if s, ok := getHTTPDeltaSecondsCacheControl(respCacheControl, "s-maxage"); ok {
+		return s
+	}
+	if s, ok := getHTTPDeltaSecondsCacheControl(respCacheControl, "max-age"); ok {
+		return s
+	}
+
+	getExpires := func() (time.Duration, bool) {
+		expires, ok := web.GetHTTPDate(respHeaders, "Expires")
+		if !ok {
+			return 0, false
+		}
+		date, ok := web.GetHTTPDate(respHeaders, "Date")
+		if !ok {
+			return 0, false
+		}
+		return expires.Sub(date), true
+	}
+	if s, ok := getExpires(); ok {
+		return s
+	}
+	return heuristicFreshness(respHeaders)
+}
+
+const Day = time.Hour * time.Duration(24)
+
+// HeuristicFreshness follows the recommendation of RFC7234§4.2.2 and returns the min of 10% of the (Date - Last-Modified) headers and 24 hours, if they exist, and 24 hours if they don't.
+// TODO: smarter and configurable heuristics
+func heuristicFreshness(respHeaders http.Header) time.Duration {
+	sinceLastModified, ok := sinceLastModified(respHeaders)
+	if !ok {
+		return Day
+	}
+	freshness := time.Duration(math.Min(float64(Day), float64(sinceLastModified)))
+	return freshness
+}
+
+func sinceLastModified(headers http.Header) (time.Duration, bool) {
+	lastModified, ok := web.GetHTTPDate(headers, "last-modified")
+	if !ok {
+		return 0, false
+	}
+	date, ok := web.GetHTTPDate(headers, "date")
+	if !ok {
+		return 0, false
+	}
+	return date.Sub(lastModified), true
+}
+
+// ageValue is used to calculate current_age per RFC7234§4.2.3
+func ageValue(respHeaders http.Header) time.Duration {
+	s, ok := getHTTPDeltaSeconds(respHeaders, "age")
+	if !ok {
+		return 0
+	}
+	return s
+}
+
+// dateValue is used to calculate current_age per RFC7234§4.2.3. It returns time, or false if the response had no Date header (in violation of HTTP/1.1).
+func dateValue(respHeaders http.Header) (time.Time, bool) {
+	return web.GetHTTPDate(respHeaders, "date")
+}
+
+func apparentAge(respHeaders http.Header, respRespTime time.Time) time.Duration {
+	dateValue, ok := dateValue(respHeaders)
+	if !ok {
+		return 0 // TODO log warning?
+	}
+	rawAge := respRespTime.Sub(dateValue)
+	return time.Duration(math.Max(0.0, float64(rawAge)))
+}
+
+func responseDelay(respReqTime time.Time, respRespTime time.Time) time.Duration {
+	return respRespTime.Sub(respReqTime)
+}
+
+func correctedAgeValue(respHeaders http.Header, respReqTime time.Time, respRespTime time.Time) time.Duration {
+	return ageValue(respHeaders) + responseDelay(respReqTime, respRespTime)
+}
+
+func correctedInitialAge(respHeaders http.Header, respReqTime time.Time, respRespTime time.Time) time.Duration {
+	return time.Duration(math.Max(float64(apparentAge(respHeaders, respRespTime)), float64(correctedAgeValue(respHeaders, respReqTime, respRespTime))))
+}
+
+func residentTime(respRespTime time.Time) time.Duration {
+	return time.Now().Sub(respRespTime)
+}
+
+func getCurrentAge(respHeaders http.Header, respReqTime time.Time, respRespTime time.Time) time.Duration {
+	correctedInitial := correctedInitialAge(respHeaders, respReqTime, respRespTime)
+	resident := residentTime(respRespTime)
+	log.Debugf("getCurrentAge: correctedInitialAge %v residentTime %v\n", correctedInitial, resident)
+	return correctedInitial + resident
+}
+
+// inMinFresh returns whether the given response is within the `min-fresh` request directive. If no `min-fresh` directive exists in the request, `true` is returned.
+func inMinFresh(respHeaders http.Header, reqCacheControl web.CacheControl, respCacheControl web.CacheControl, respReqTime time.Time, respRespTime time.Time) bool {
+	minFresh, ok := getHTTPDeltaSecondsCacheControl(reqCacheControl, "min-fresh")
+	if !ok {
+		return true // no min-fresh => within min-fresh
+	}
+	freshnessLifetime := getFreshnessLifetime(respHeaders, respCacheControl)
+	currentAge := getCurrentAge(respHeaders, respReqTime, respRespTime)
+	inMinFresh := minFresh < (freshnessLifetime - currentAge)
+	log.Debugf("inMinFresh minFresh %v freshnessLifetime %v currentAge %v => %v < (%v - %v) = %v\n", minFresh, freshnessLifetime, currentAge, minFresh, freshnessLifetime, currentAge, inMinFresh)
+	return inMinFresh
+}
+
+// TODO add warning generation funcs
+
+// AllowedStale checks the constraints in RFC7234§4 via RFC7234§4.2.4
+func allowedStale(respHeaders http.Header, reqCacheControl web.CacheControl, respCacheControl web.CacheControl, respReqTime time.Time, respRespTime time.Time, strictRFC bool) remapdata.Reuse {
+	// TODO return remapdata.ReuseMustRevalidate where permitted
+	_, reqHasMaxAge := reqCacheControl["max-age"]
+	_, reqHasMaxStale := reqCacheControl["max-stale"]
+	_, respHasMustReval := respCacheControl["must-revalidate"]
+	_, respHasProxyReval := respCacheControl["proxy-revalidate"]
+	log.Debugf("AllowedStale: reqHasMaxAge %v reqHasMaxStale %v strictRFC %v\n", reqHasMaxAge, reqHasMaxStale, strictRFC)
+	if respHasMustReval || respHasProxyReval {
+		log.Debugf("AllowedStale: returning mustreval - must-revalidate\n")
+		return remapdata.ReuseMustRevalidate
+	}
+	if strictRFC && reqHasMaxAge && !reqHasMaxStale {
+		log.Debugf("AllowedStale: returning can - strictRFC & reqHasMaxAge & !reqHasMaxStale\n")
+		return remapdata.ReuseMustRevalidateCanStale
+	}
+	if _, ok := respCacheControl["no-cache"]; ok {
+		log.Debugf("AllowedStale: returning reusecannot - no-cache\n")
+		return remapdata.ReuseCannot // TODO verify RFC doesn't allow Revalidate here
+	}
+	if _, ok := respCacheControl["no-store"]; ok {
+		log.Debugf("AllowedStale: returning reusecannot - no-store\n")
+		return remapdata.ReuseCannot // TODO verify RFC doesn't allow revalidate here
+	}
+	if !inMaxStale(respHeaders, respCacheControl, respReqTime, respRespTime) {
+		log.Debugf("AllowedStale: returning mustreval - not in max stale\n")
+		return remapdata.ReuseMustRevalidate // TODO verify RFC allows
+	}
+	log.Debugf("AllowedStale: returning can - all preconditions passed\n")
+	return remapdata.ReuseMustRevalidateCanStale
+}
+
+// InMaxStale returns whether the given response is within the `max-stale` request directive. If no `max-stale` directive exists in the request, `true` is returned.
+func inMaxStale(respHeaders http.Header, respCacheControl web.CacheControl, respReqTime time.Time, respRespTime time.Time) bool {
+	maxStale, ok := getHTTPDeltaSecondsCacheControl(respCacheControl, "max-stale")
+	if !ok {
+		// maxStale = 5 // debug
+		return true // no max-stale => within max-stale
+	}
+	freshnessLifetime := getFreshnessLifetime(respHeaders, respCacheControl)
+	currentAge := getCurrentAge(respHeaders, respReqTime, respRespTime)
+	log.Errorf("DEBUGR InMaxStale maxStale %v freshnessLifetime %v currentAge %v => %v > (%v, %v)\n", maxStale, freshnessLifetime, currentAge, maxStale, currentAge, freshnessLifetime) // DEBUG
+	inMaxStale := maxStale > (currentAge - freshnessLifetime)
+	return inMaxStale
+}
+
+// SelectedHeadersMatch checks the constraints in RFC7234§4.1
+// TODO: change caching to key on URL+headers, so multiple requests for the same URL with different vary headers can be cached?
+func selectedHeadersMatch(reqHeaders http.Header, respReqHeaders http.Header, strictRFC bool) bool {
+	varyHeaders, ok := reqHeaders["vary"]
+	if !strictRFC && !ok {
+		return true
+	}
+	if len(varyHeaders) == 0 {
+		return true
+	}
+	varyHeader := varyHeaders[0]
+
+	if varyHeader == "*" {
+		return false
+	}
+	varyHeader = strings.ToLower(varyHeader)
+	varyHeaderHeaders := strings.Split(varyHeader, ",")
+	for _, header := range varyHeaderHeaders {
+		if _, ok := respReqHeaders[header]; !ok {
+			return false
+		}
+	}
+	return true
+}
+
+// HasPragmaNoCache returns whether the given headers have a `pragma: no-cache` which is to be considered per HTTP/1.1. This specifically returns false if `cache-control` exists, even if `pragma: no-cache` exists, per RFC7234§5.4
+func hasPragmaNoCache(reqHeaders http.Header) bool {
+	if _, ok := reqHeaders["Cache-Control"]; ok {
+		return false
+	}
+	pragmas, ok := reqHeaders["pragma"]
+	if !ok {
+		return false
+	}
+	if len(pragmas) == 0 {
+		return false
+	}
+	pragma := pragmas[0]
+
+	if strings.HasPrefix(pragma, "no-cache") { // RFC7234§5.4 specifically requires no-cache be the first pragma
+		return true
+	}
+	return false
+}
diff --git a/grove/remap/rules_test.go b/grove/remap/rules_test.go
new file mode 100644
index 000000000..91bdde9d2
--- /dev/null
+++ b/grove/remap/rules_test.go
@@ -0,0 +1,727 @@
+package remap
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"os"
+	"testing"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+func TestRules(t *testing.T) {
+	// test client no-store is obeyed with strict RFC - tests RFC7234§5.2.1.5 compliance
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-store"},
+		}
+		respCode := 200
+		respHdr := http.Header{}
+		strictRFC := true
+
+		if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned true for no-store request and strict RFC")
+		}
+	}
+
+	// test client no-store is ignored without strict RFC - tests RFC7234§5.2.1.5 violation to protect origins
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-store"},
+		}
+		respCode := 200
+		respHdr := http.Header{}
+		strictRFC := false
+
+		if !CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned false for no-store request and strict RFC disabled")
+		}
+	}
+
+	// test client no-cache no-store is ignored without strict RFC - tests RFC7234§5.2.1.5 violation to protect origins
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-cache no-store"},
+		}
+		respCode := 200
+		respHdr := http.Header{}
+		strictRFC := false
+
+		if !CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned false for no-store request and strict RFC disabled")
+		}
+	}
+
+	// test client no-cache is ignored without strict RFC - tests RFC7234§5.2.1.4 violation to protect origins
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-cache"},
+		}
+		respHdr := http.Header{}
+		reqCC := web.CacheControl{
+			"no-cache": "",
+		}
+		respCC := web.CacheControl{}
+		respReqHdrs := http.Header{}
+		respReqTime := time.Now()
+		respRespTime := time.Now()
+
+		strictRFC := false
+
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored for no-cache request and strict RFC disabled: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test client no-store is ignored without strict RFC - tests RFC7234§5.2.1.4 violation to protect origins
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-store no-cache"},
+		}
+		respHdr := http.Header{}
+		reqCC := web.CacheControl{
+			"no-store": "",
+			"no-cache": "",
+		}
+		respCC := web.CacheControl{}
+		respReqHdrs := http.Header{}
+		respReqTime := time.Now()
+		respRespTime := time.Now()
+
+		strictRFC := false
+
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored for no-cache request and strict RFC disabled: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test client no-cache and no-store is ignored without strict RFC - tests RFC7234§5.2.1.4 violation to protect origins
+	{
+		reqHdr := http.Header{
+			"Cache-Control": {"no-store no-cache"},
+		}
+		respHdr := http.Header{}
+		reqCC := web.CacheControl{
+			"no-store": "",
+			"no-cache": "",
+		}
+		respCC := web.CacheControl{}
+		respReqHdrs := http.Header{}
+		respReqTime := time.Now()
+		respRespTime := time.Now()
+
+		strictRFC := false
+
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored for no-cache request and strict RFC disabled: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent no-cache is obeyed with strict RFC
+	{
+		reqHdr := http.Header{}
+		respCode := 200
+		respHdr := http.Header{
+			"Cache-Control": {"no-cache"},
+		}
+		strictRFC := false
+
+		if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned true for no-cache request and strict RFC disabled")
+		}
+	}
+
+	// test parent no-store is obeyed with strict RFC
+	{
+		reqHdr := http.Header{}
+		respCode := 200
+		respHdr := http.Header{
+			"Cache-Control": {"no-store"},
+		}
+		strictRFC := false
+
+		if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned true for no-cache request and strict RFC disabled")
+		}
+	}
+
+	// test parent no-cache is obeyed without strict RFC
+	{
+		reqHdr := http.Header{}
+		respCode := 200
+		respHdr := http.Header{
+			"Cache-Control": {"no-cache"},
+		}
+		strictRFC := false
+
+		if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned true for no-cache request and strict RFC enabled")
+		}
+	}
+
+	// test parent no-store is obeyed without strict RFC
+	{
+		reqHdr := http.Header{}
+		respCode := 200
+		respHdr := http.Header{
+			"Cache-Control": {"no-store"},
+		}
+		strictRFC := true
+
+		if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+			t.Errorf("CanCache returned true for no-cache request and strict RFC enabled")
+		}
+	}
+
+	// test parent Expires in future is reused
+	{
+		now := time.Now()
+		tenMinsBeforeExpires := now.Add(time.Minute * -10)
+		expires := now.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Expires": {expires},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinsBeforeExpires
+		respRespTime := tenMinsBeforeExpires
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request after expires: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent Expires in past has revaldiate and can stale
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := tenMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Expires": {expires},
+			"Date":    {expires},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after expires: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent Expires in past with must-revaldiate, cannot stale
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := tenMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Expires":       {expires},
+			"Date":          {expires},
+			"Cache-Control": {"must-revalidate"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"must-revalidate": ""}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidate {
+			t.Errorf("CanReuseStored request after expires and response must-revalidate: expected ReuseMustRevalidate, actual %v", reuse)
+		}
+	}
+
+	// test parent Expires in past proxy-revaldiate, and no-stale
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := tenMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Expires":       {expires},
+			"Date":          {expires},
+			"Cache-Control": {"must-revalidate"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"must-revalidate": ""}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidate {
+			t.Errorf("CanReuseStored request after expires and response must-revalidate: expected ReuseMustRevalidate, actual %v", reuse)
+		}
+	}
+
+	// test parent Expires in past with proxy-revaldiate returns MustRevalidateNoStale
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := tenMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Expires":       {expires},
+			"Date":          {expires},
+			"Cache-Control": {"proxy-revalidate"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"proxy-revalidate": ""}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidate {
+			t.Errorf("CanReuseStored request after expires and response must-revalidate: expected ReuseMustRevalidate, actual %v", reuse)
+		}
+	}
+
+	// test parent max-age in future returns CanReuse
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=1200"}, // 20 minutes
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"max-age": "1200"}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request after expires and response must-revalidate: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent max-age in past returns MustRevalidate
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=300"}, // 5 minutes
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"max-age": "300"}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after response max-age: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent s-maxage in future returns CanReuse
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"s-maxage=1200"}, // 20 minutes
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "1200"}
+		respReqHdrs := http.Header{}
+		respReqTime := now
+		respRespTime := now
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request before s-maxage: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent s-age in past returns MustRevalidate
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"s-maxage=300"}, // 5 minutes
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "300"}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after response s-maxage: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent future s-maxage overrides past max-age and  returns CanReuse
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=300,s-maxage=1200"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "1200",
+			"max-age":  "300",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request before s-maxage but after max-age: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent past s-maxage overrides future max-age and returns MustReval
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=1200,s-maxage=300"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "300",
+			"max-age":  "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request before s-maxage but after max-age: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent future max-age overrides past Expires and returns CanReuse
+	{
+		now := time.Now()
+		twentyMinutesAgo := now.Add(time.Minute * -10)
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := twentyMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"max-age=1200"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"max-age": "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request before max-age but after Expires: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent past max-age overrides future Expires and returns MustRevalidate
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		fiveMinutesHence := now.Add(time.Minute * 5)
+		expires := fiveMinutesHence.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"max-age=300"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"max-age": "300",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after max-age but before Expires: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent future s-maxage overrides past Expires and returns CanReuse
+	{
+		now := time.Now()
+		twentyMinutesAgo := now.Add(time.Minute * -10)
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := twentyMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"s-maxage=1200"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request before s-maxage but after Expires: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent past s-maxage overrides future Expires and returns MustRevalidate
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		fiveMinutesHence := now.Add(time.Minute * 5)
+		expires := fiveMinutesHence.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"s-maxage=300"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "300",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after max-age but before Expires: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test parent future s-maxage overrides past Expires and past max-age and returns CanReuse
+	{
+		now := time.Now()
+		twentyMinutesAgo := now.Add(time.Minute * -10)
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		expires := twentyMinutesAgo.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"s-maxage=1200,max-age=300"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "1200",
+			"max-age":  "300",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request before s-maxage but after Expires: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test parent past s-maxage overrides future Expires and future max-age and returns MustRevalidate
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		fiveMinutesHence := now.Add(time.Minute * 5)
+		expires := fiveMinutesHence.Format(time.RFC1123)
+		reqHdr := http.Header{}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Expires":       {expires},
+			"Cache-Control": {"s-maxage=300,max-age=1200"},
+		}
+		reqCC := web.CacheControl{}
+		respCC := web.CacheControl{
+			"s-maxage": "300",
+			"max-age":  "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidateCanStale {
+			t.Errorf("CanReuseStored request after s-maxage but before Expires: expected ReuseMustRevalidateCanStale, actual %v", reuse)
+		}
+	}
+
+	// test client min-fresh is obeyed with strict RFC - tests RFC7234§5.2.1.3 compliance
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{
+			"Cache-Control": {"min-fresh=900"},
+		}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=1200"},
+		}
+		reqCC := web.CacheControl{
+			"min-fresh": "900",
+		}
+		respCC := web.CacheControl{
+			"max-age": "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := true
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseMustRevalidate {
+			t.Errorf("CanReuseStored request with strictRFC min-fresh 300 with 600 remaining: expected ReuseMustRevalidate, actual %v", reuse)
+		}
+	}
+
+	// test client min-fresh is ignored without strict RFC - tests RFC7234§5.2.1.3 violation to protect origins
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{
+			"Cache-Control": {"min-fresh=900"},
+		}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=1200"},
+		}
+		reqCC := web.CacheControl{
+			"min-fresh": "900",
+		}
+		respCC := web.CacheControl{
+			"max-age": "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request with strictRFC min-fresh 1200 with 600 remaining: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test client min-fresh is ignored without strict RFC - tests RFC7234§5.2.1.3 violation to protect origins
+	{
+		now := time.Now()
+		tenMinutesAgo := now.Add(time.Minute * -10)
+		reqHdr := http.Header{
+			"Cache-Control": {"min-fresh=900"},
+		}
+		respHdr := http.Header{
+			"Date":          {tenMinutesAgo.Format(time.RFC1123)},
+			"Cache-Control": {"max-age=1200"},
+		}
+		reqCC := web.CacheControl{
+			"min-fresh": "900",
+		}
+		respCC := web.CacheControl{
+			"max-age": "1200",
+		}
+		respReqHdrs := http.Header{}
+		respReqTime := tenMinutesAgo
+		respRespTime := tenMinutesAgo
+		strictRFC := false
+		if reuse := CanReuseStored(reqHdr, respHdr, reqCC, respCC, respReqHdrs, respReqTime, respRespTime, strictRFC); reuse != remapdata.ReuseCan {
+			t.Errorf("CanReuseStored request with strictRFC min-fresh 1200 with 600 remaining: expected ReuseCan, actual %v", reuse)
+		}
+	}
+
+	// test default-cacheable response is cached. Tests RFC7234§5.2.1.3 and RFC7231§6.1 compliance
+	{
+		defaultCacheableCodes := []int{200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501} // RFC7231§6.1
+		for _, code := range defaultCacheableCodes {
+			reqHdr := http.Header{}
+			respCode := code
+			respHdr := http.Header{}
+			strictRFC := true
+
+			if !CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+				t.Errorf("CanCache returned false for request with no cache control and default-cacheable response code %v", code)
+			}
+		}
+	}
+
+	// test non-default-cacheable response with no Cache-Control is not cached. Tests RFC7234§5.2.1.3 compliance
+	{
+		nonDefaultCacheableCodes := []int{
+			201, 202, 205, 207, 208, 226,
+			302, 303, 304, 305, 306, 307, 308,
+			400, 401, 402, 403, 406, 407, 408, 409, 411, 412, 413, 4015, 416, 417, 418, 421, 422, 423, 424, 428, 429, 431, 451,
+			500, 502, 503, 504, 505, 506, 507, 508, 510, 511,
+		}
+		for _, code := range nonDefaultCacheableCodes {
+			reqHdr := http.Header{}
+			respCode := code
+			respHdr := http.Header{}
+			strictRFC := true
+
+			if CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+				t.Errorf("CanCache returned true for request with no cache control and non-default-cacheable response code %v", code)
+			}
+		}
+	}
+
+	// test non-default-cacheable response with Cache-Control is cached. Tests RFC7234§3 compliance
+	{
+		nonDefaultCacheableCodes := []int{
+			201, 202, 205, 207, 208, 226,
+			302, 303, 304, 305, 306, 307, 308,
+			400, 401, 402, 403, 406, 407, 408, 409, 411, 412, 413, 4015, 416, 417, 418, 421, 422, 423, 424, 428, 429, 431, 451,
+			500, 502, 503, 504, 505, 506, 507, 508, 510, 511,
+		}
+		cacheableRespHdrs := []map[string][]string{
+			{"Expires": {time.Now().Format(time.RFC1123)}},
+			{"Cache-Control": {"max-age=42"}},
+			{"Cache-Control": {"s-maxage=42"}},
+		}
+
+		for _, code := range nonDefaultCacheableCodes {
+			for _, hdr := range cacheableRespHdrs {
+				reqHdr := http.Header{}
+				respCode := code
+				respHdr := hdr
+				strictRFC := true
+
+				if !CanCache(http.MethodGet, reqHdr, respCode, respHdr, strictRFC) {
+					t.Errorf("CanCache returned false for request with non-default-cacheable response code %v and cacheable header %v", respCode, respHdr)
+				}
+			}
+		}
+	}
+
+	log.Init(log.NopCloser(os.Stdout), log.NopCloser(os.Stdout), log.NopCloser(os.Stdout), log.NopCloser(os.Stdout), log.NopCloser(os.Stdout))
+}
diff --git a/grove/remapdata/remapdata.go b/grove/remapdata/remapdata.go
new file mode 100644
index 000000000..2961a0b4d
--- /dev/null
+++ b/grove/remapdata/remapdata.go
@@ -0,0 +1,235 @@
+package remapdata
+
+/*
+   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.
+*/
+
+// remapdata exists as a package to avoid import cycles, for packages that need remap objects and are also included by remap.
+
+import (
+	"encoding/json"
+	"net"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/chash"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+type Reuse int
+
+const (
+	ReuseCan Reuse = iota
+	ReuseCannot
+	ReuseMustRevalidate
+	// ReuseMustRevalidateCanStale indicates the response must be revalidated, but if the parent cannot be reached, may be served stale, per RFC7234§4.2.4
+	ReuseMustRevalidateCanStale
+)
+
+// ParentSelectionType is the algorithm to use for selecting parents.
+type ParentSelectionType string
+
+const (
+	ParentSelectionTypeConsistentHash = ParentSelectionType("consistent-hash")
+	ParentSelectionTypeRoundRobin     = ParentSelectionType("round-robin")
+	ParentSelectionTypeInvalid        = ParentSelectionType("")
+)
+
+func (t ParentSelectionType) String() string {
+	switch t {
+	case ParentSelectionTypeConsistentHash:
+		return "consistent-hash"
+	case ParentSelectionTypeRoundRobin:
+		return "round-robin"
+	default:
+		return "invalid"
+	}
+}
+
+func ParentSelectionTypeFromString(s string) ParentSelectionType {
+	s = strings.ToLower(s)
+	if s == "consistent-hash" {
+		return ParentSelectionTypeConsistentHash
+	}
+	if s == "round-robin" {
+		return ParentSelectionTypeRoundRobin
+	}
+	return ParentSelectionTypeInvalid
+}
+
+type RemapRulesStats struct {
+	Allow []*net.IPNet
+	Deny  []*net.IPNet
+}
+
+func (statRules RemapRulesStats) Allowed(ip net.IP) bool {
+	for _, network := range statRules.Deny {
+		if network.Contains(ip) {
+			log.Debugf("deny contains ip\n")
+			return false
+		}
+	}
+	if len(statRules.Allow) == 0 {
+		log.Debugf("Allowed len 0\n")
+		return true
+	}
+	for _, network := range statRules.Allow {
+		if network.Contains(ip) {
+			log.Debugf("allow contains ip\n")
+			return true
+		}
+	}
+	return false
+}
+
+type RemapRuleBase struct {
+	Name               string          `json:"name"`
+	From               string          `json:"from"`
+	CertificateFile    string          `json:"certificate-file"`
+	CertificateKeyFile string          `json:"certificate-key-file"`
+	ConnectionClose    bool            `json:"connection-close"`
+	QueryString        QueryStringRule `json:"query-string"`
+	// ConcurrentRuleRequests is the number of concurrent requests permitted to a remap rule, that is, to an origin. If this is 0, the global config is used.
+	ConcurrentRuleRequests int                        `json:"concurrent_rule_requests"`
+	RetryNum               *int                       `json:"retry_num"`
+	DSCP                   int                        `json:"dscp"`
+	PluginsShared          map[string]json.RawMessage `json:"plugins_shared"`
+}
+
+type RemapRule struct {
+	RemapRuleBase
+	Timeout         *time.Duration
+	ParentSelection *ParentSelectionType
+	To              []RemapRuleTo
+	Allow           []*net.IPNet
+	Deny            []*net.IPNet
+	RetryCodes      map[int]struct{}
+	ConsistentHash  chash.ATSConsistentHash
+	Cache           icache.Cache
+	Plugins         map[string]interface{}
+}
+
+func (r *RemapRule) Allowed(ip net.IP) bool {
+	for _, network := range r.Deny {
+		if network.Contains(ip) {
+			log.Debugf("deny contains ip\n")
+			return false
+		}
+	}
+	if len(r.Allow) == 0 {
+		log.Debugf("Allowed len 0\n")
+		return true
+	}
+	for _, network := range r.Allow {
+		if network.Contains(ip) {
+			log.Debugf("allow contains ip\n")
+			return true
+		}
+	}
+	return false
+}
+
+// URI takes a request URI and maps it to the real URI to proxy-and-cache. The `failures` parameter indicates how many parents have tried and failed, indicating to skip to the nth hashed parent. Returns the URI to request, and the proxy URL (if any)
+func (r RemapRule) URI(fromURI string, path string, query string, failures int) (string, *url.URL, *http.Transport) {
+	fromHash := path
+	if r.QueryString.Remap && query != "" {
+		fromHash += "?" + query
+	}
+
+	// fmt.Println("RemapRule.URI fromURI " + fromHash)
+	to, proxyURI, transport := r.uriGetTo(fromHash, failures)
+	uri := to + fromURI[len(r.From):]
+	if !r.QueryString.Remap {
+		if i := strings.Index(uri, "?"); i != -1 {
+			uri = uri[:i]
+		}
+	}
+	return uri, proxyURI, transport
+}
+
+// uriGetTo is a helper func for URI. It returns the To URL, based on the Parent Selection type. In the event of failure, it logs the error and returns the first parent. Also returns the URL's Proxy URI (if any).
+func (r RemapRule) uriGetTo(fromURI string, failures int) (string, *url.URL, *http.Transport) {
+	switch *r.ParentSelection {
+	case ParentSelectionTypeConsistentHash:
+		return r.uriGetToConsistentHash(fromURI, failures)
+	default:
+		log.Errorf("RemapRule.URI: Rule '%v': Unknown Parent Selection type %v - using first URI in rule\n", r.Name, r.ParentSelection)
+		return r.To[0].URL, r.To[0].ProxyURL, r.To[0].Transport
+	}
+}
+
+// uriGetToConsistentHash is a helper func for URI, uriGetTo. It returns the To URL using Consistent Hashing. In the event of failure, it logs the error and returns the first parent. Also returns the Proxy URI (if any).
+func (r RemapRule) uriGetToConsistentHash(fromURI string, failures int) (string, *url.URL, *http.Transport) {
+	// fmt.Printf("DEBUGL uriGetToConsistentHash RemapRule %+v\n", r)
+	if r.ConsistentHash == nil {
+		log.Errorf("RemapRule.URI: Rule '%v': Parent Selection Type ConsistentHash, but rule.ConsistentHash is nil! Using first parent\n", r.Name)
+		return r.To[0].URL, r.To[0].ProxyURL, r.To[0].Transport
+	}
+
+	// fmt.Printf("DEBUGL uriGetToConsistentHash\n")
+	iter, _, err := r.ConsistentHash.Lookup(fromURI)
+	if err != nil {
+		// if r.ConsistentHash.First() == nil {
+		// 	fmt.Printf("DEBUGL uriGetToConsistentHash NodeMap empty!\n")
+		// }
+		// fmt.Printf("DEBUGL uriGetToConsistentHash fromURI '%v' err %v returning '%v'\n", fromURI, err, r.To[0].URL)
+		log.Errorf("RemapRule.URI: Rule '%v': Error looking up Consistent Hash! Using first parent\n", r.Name)
+		return r.To[0].URL, r.To[0].ProxyURL, r.To[0].Transport
+	}
+
+	for i := 0; i < failures; i++ {
+		iter = iter.NextWrap()
+	}
+
+	return iter.Val().Name, iter.Val().ProxyURL, iter.Val().Transport
+}
+
+func (r RemapRule) CacheKey(method string, fromURI string) string {
+	// TODO don't cache on `to`, since it's affected by Parent Selection
+	// TODO add parent selection
+	to := r.To[0].URL
+	uri := to + fromURI[len(r.From):]
+	if !r.QueryString.Cache {
+		if i := strings.Index(uri, "?"); i != -1 {
+			uri = uri[:i]
+		}
+	}
+	if method == http.MethodHead { // HEAD uses the same key as GET
+		method = http.MethodGet
+	}
+	key := method + ":" + uri
+	return key
+}
+
+type RemapRuleToBase struct {
+	URL      string   `json:"url"`
+	Weight   *float64 `json:"weight"`
+	RetryNum *int     `json:"retry_num"`
+}
+
+type RemapRuleTo struct {
+	RemapRuleToBase
+	ProxyURL   *url.URL
+	Timeout    *time.Duration
+	RetryCodes map[int]struct{}
+	Transport  *http.Transport
+}
+
+type QueryStringRule struct {
+	Remap bool `json:"remap"`
+	Cache bool `json:"cache"`
+}
diff --git a/grove/stat/stats.go b/grove/stat/stats.go
new file mode 100644
index 000000000..7823f7270
--- /dev/null
+++ b/grove/stat/stats.go
@@ -0,0 +1,376 @@
+package stat
+
+/*
+   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.
+*/
+
+import (
+	"net/http"
+	"strings"
+	"sync/atomic"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+	"github.com/apache/incubator-trafficcontrol/grove/remapdata"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+type StatsSystem interface {
+	AddConfigReloadRequests()
+	SetLastReloadRequest(time.Time)
+	AddConfigReload()
+	SetLastReload(time.Time)
+	SetAstatsLoad(time.Time)
+
+	ConfigReloadRequests() uint64
+	LastReloadRequest() time.Time
+	ConfigReloads() uint64
+	LastReload() time.Time
+	AstatsLoad() time.Time
+	Version() string
+}
+
+type Stats interface {
+	System() StatsSystem
+	Remap() StatsRemaps
+
+	Connections() uint64
+
+	CacheHits() uint64
+	AddCacheHit()
+	CacheMisses() uint64
+	AddCacheMiss()
+
+	CacheSize() uint64
+	CacheCapacity() uint64
+
+	// Write writes to the remapRuleStats of s, and returns the bytes written to the connection
+	Write(w http.ResponseWriter, conn *web.InterceptConn, reqFQDN string, remoteAddr string, code int, bytesWritten uint64, cacheHit bool) uint64
+
+	CacheKeys(string) []string
+	CacheSizeByName(string) (uint64, bool)
+	CacheCapacityByName(string) (uint64, bool)
+	CacheNames() []string
+	CachePeek(string, string) (*cacheobj.CacheObj, bool)
+}
+
+func New(remapRules []remapdata.RemapRule, caches map[string]icache.Cache, cacheCapacityBytes uint64, httpConns *web.ConnMap, httpsConns *web.ConnMap, version string) Stats {
+	cacheHits := uint64(0)
+	cacheMisses := uint64(0)
+	return &stats{
+		system:             NewStatsSystem(version),
+		remap:              NewStatsRemaps(remapRules),
+		cacheHits:          &cacheHits,
+		cacheMisses:        &cacheMisses,
+		caches:             caches,
+		cacheCapacityBytes: cacheCapacityBytes,
+		httpConns:          httpConns,
+		httpsConns:         httpsConns,
+	}
+}
+
+// Write writes to the remapRuleStats of s, and returns the bytes written to the connection
+func (stats *stats) Write(w http.ResponseWriter, conn *web.InterceptConn, reqFQDN string, remoteAddr string, code int, bytesWritten uint64, cacheHit bool) uint64 {
+	remapRuleStats, ok := stats.Remap().Stats(reqFQDN)
+	if !ok {
+		log.Errorf("Remap rule %v not in Stats\n", reqFQDN)
+		return bytesWritten
+	}
+
+	if wFlusher, ok := w.(http.Flusher); !ok {
+		log.Errorf("ResponseWriter is not a Flusher, could not flush written bytes, stat out_bytes will be inaccurate!\n")
+	} else {
+		wFlusher.Flush()
+	}
+
+	bytesRead := 0 // TODO get somehow? Count body? Sum header?
+	if conn != nil {
+		bytesRead = conn.BytesRead()
+		bytesWritten = uint64(conn.BytesWritten()) // get the more accurate interceptConn bytes written, if we can
+		// Don't log - the Handler has already logged the failure to get the conn
+	}
+
+	// bytesRead, bytesWritten := getConnInfoAndDestroyWriter(w, stats, remapRuleName)
+	remapRuleStats.AddInBytes(uint64(bytesRead))
+	remapRuleStats.AddOutBytes(uint64(bytesWritten))
+
+	if cacheHit {
+		stats.AddCacheHit()
+		remapRuleStats.AddCacheHit()
+	} else {
+		stats.AddCacheMiss()
+		remapRuleStats.AddCacheMiss()
+	}
+
+	switch {
+	case code < 200:
+		log.Errorf("responded with invalid code %v\n", code)
+	case code < 300:
+		remapRuleStats.AddStatus2xx(1)
+	case code < 400:
+		remapRuleStats.AddStatus3xx(1)
+	case code < 500:
+		remapRuleStats.AddStatus4xx(1)
+	case code < 600:
+		remapRuleStats.AddStatus5xx(1)
+	default:
+		log.Errorf("responded with invalid code %v\n", code)
+	}
+	return bytesWritten
+}
+
+// stats fulfills the Stats interface
+type stats struct {
+	system             StatsSystem
+	remap              StatsRemaps
+	cacheHits          *uint64
+	cacheMisses        *uint64
+	caches             map[string]icache.Cache
+	cacheCapacityBytes uint64
+	httpConns          *web.ConnMap
+	httpsConns         *web.ConnMap
+}
+
+func (s stats) Connections() uint64 {
+	l := uint64(0)
+	if s.httpConns != nil {
+		l += uint64(s.httpConns.Len())
+	}
+	if s.httpsConns != nil {
+		l += uint64(s.httpsConns.Len())
+	}
+	return l
+}
+func (s stats) CacheHits() uint64    { return atomic.LoadUint64(s.cacheHits) }
+func (s stats) AddCacheHit()         { atomic.AddUint64(s.cacheHits, 1) }
+func (s stats) CacheMisses() uint64  { return atomic.LoadUint64(s.cacheMisses) }
+func (s stats) AddCacheMiss()        { atomic.AddUint64(s.cacheMisses, 1) }
+func (s *stats) System() StatsSystem { return StatsSystem(s.system) }
+func (s *stats) Remap() StatsRemaps  { return s.remap }
+
+// CacheSizeByName returns the size of tha cache for a particular cache
+func (s stats) CacheSizeByName(cName string) (uint64, bool) {
+	if cache, ok := s.caches[cName]; ok {
+		return cache.Size(), true
+	}
+	return 0, false
+}
+
+// CacheSize() returns the combined size of all caches.
+func (s stats) CacheSize() uint64 {
+	sum := uint64(0)
+	for _, c := range s.caches {
+		sum += c.Size()
+	}
+	return sum
+}
+
+// CacheNames returns an array of all the cache names
+func (s stats) CacheNames() []string {
+	cNames := make([]string, 0)
+	for cacheName, _ := range s.caches {
+		cNames = append(cNames, cacheName)
+	}
+	return cNames
+}
+
+// CacheKeys returns an array of all the cache keys for the cache cacheName
+func (s stats) CacheKeys(cacheName string) []string {
+	return s.caches[cacheName].Keys()
+}
+
+// CachePeek returns the cached object *without* changing the recent-used-ness.
+func (s stats) CachePeek(key, cacheName string) (*cacheobj.CacheObj, bool) {
+	return s.caches[cacheName].Peek(key)
+}
+
+func (s stats) CacheCapacityByName(cName string) (uint64, bool) {
+	if cache, ok := s.caches[cName]; ok {
+		return cache.Capacity(), true
+	}
+	return 0, false
+}
+
+func (s stats) CacheCapacity() uint64 { return s.cacheCapacityBytes }
+
+type StatsRemaps interface {
+	Stats(fqdn string) (StatsRemap, bool)
+	Rules() []string
+}
+
+type StatsRemap interface {
+	InBytes() uint64
+	AddInBytes(uint64)
+	OutBytes() uint64
+	AddOutBytes(uint64)
+	Status2xx() uint64
+	AddStatus2xx(uint64)
+	Status3xx() uint64
+	AddStatus3xx(uint64)
+	Status4xx() uint64
+	AddStatus4xx(uint64)
+	Status5xx() uint64
+	AddStatus5xx(uint64)
+
+	CacheHits() uint64
+	AddCacheHit()
+	CacheMisses() uint64
+	AddCacheMiss()
+}
+
+func getFromFQDN(r remapdata.RemapRule) string {
+	path := r.From
+	schemeEnd := `://`
+	if i := strings.Index(path, schemeEnd); i != -1 {
+		path = path[i+len(schemeEnd):]
+	}
+	pathStart := `/`
+	if i := strings.Index(path, pathStart); i != -1 {
+		path = path[:i]
+	}
+	return path
+}
+
+func NewStatsRemaps(remapRules []remapdata.RemapRule) StatsRemaps {
+	m := make(map[string]StatsRemap, len(remapRules))
+	for _, rule := range remapRules {
+		m[getFromFQDN(rule)] = NewStatsRemap() // must pre-allocate, for threadsafety, so users are never changing the map itself, only the value pointed to.
+	}
+	return statsRemaps(m)
+}
+
+// statsRemaps fulfills the StatsRemaps interface
+type statsRemaps map[string]StatsRemap
+
+func (s statsRemaps) Stats(rule string) (StatsRemap, bool) {
+	r, ok := s[rule]
+	return r, ok
+}
+
+func (s statsRemaps) Rules() []string {
+	rules := make([]string, len(s))
+	for rule := range s {
+		rules = append(rules, rule)
+	}
+	return rules
+}
+
+func NewStatsRemap() StatsRemap {
+	return &statsRemap{}
+}
+
+type statsRemap struct {
+	inBytes     uint64
+	outBytes    uint64
+	status2xx   uint64
+	status3xx   uint64
+	status4xx   uint64
+	status5xx   uint64
+	cacheHits   uint64
+	cacheMisses uint64
+}
+
+func (r *statsRemap) InBytes() uint64       { return atomic.LoadUint64(&r.inBytes) }
+func (r *statsRemap) AddInBytes(v uint64)   { atomic.AddUint64(&r.inBytes, v) }
+func (r *statsRemap) OutBytes() uint64      { return atomic.LoadUint64(&r.outBytes) }
+func (r *statsRemap) AddOutBytes(v uint64)  { atomic.AddUint64(&r.outBytes, v) }
+func (r *statsRemap) Status2xx() uint64     { return atomic.LoadUint64(&r.status2xx) }
+func (r *statsRemap) AddStatus2xx(v uint64) { atomic.AddUint64(&r.status2xx, v) }
+func (r *statsRemap) Status3xx() uint64     { return atomic.LoadUint64(&r.status3xx) }
+func (r *statsRemap) AddStatus3xx(v uint64) { atomic.AddUint64(&r.status3xx, v) }
+func (r *statsRemap) Status4xx() uint64     { return atomic.LoadUint64(&r.status4xx) }
+func (r *statsRemap) AddStatus4xx(v uint64) { atomic.AddUint64(&r.status4xx, v) }
+func (r *statsRemap) Status5xx() uint64     { return atomic.LoadUint64(&r.status5xx) }
+func (r *statsRemap) AddStatus5xx(v uint64) { atomic.AddUint64(&r.status5xx, v) }
+
+func (r *statsRemap) CacheHits() uint64 { return atomic.LoadUint64(&r.cacheHits) }
+func (r *statsRemap) AddCacheHit()      { atomic.AddUint64(&r.cacheHits, 1) }
+
+func (r *statsRemap) CacheMisses() uint64 { return atomic.LoadUint64(&r.cacheMisses) }
+func (r *statsRemap) AddCacheMiss()       { atomic.AddUint64(&r.cacheMisses, 1) }
+
+func NewStatsSystem(version string) StatsSystem {
+	return &statsSystem{version: version}
+}
+
+type statsSystem struct {
+	configReloadRequests      uint64
+	lastReloadRequestUnixNano int64
+	configReloads             uint64
+	lastReloadUnixNano        int64
+	astatsLoadUnixNano        int64
+	version                   string
+}
+
+func (s *statsSystem) ConfigReloadRequests() uint64 {
+	return atomic.LoadUint64(&s.configReloadRequests)
+}
+func (s *statsSystem) AddConfigReloadRequests() {
+	atomic.AddUint64(&s.configReloadRequests, 1)
+}
+func (s *statsSystem) LastReloadRequest() time.Time {
+	return time.Unix(0, atomic.LoadInt64(&s.lastReloadRequestUnixNano))
+}
+func (s *statsSystem) SetLastReloadRequest(t time.Time) {
+	atomic.StoreInt64(&s.lastReloadRequestUnixNano, t.UnixNano())
+}
+func (s *statsSystem) ConfigReloads() uint64 {
+	return atomic.LoadUint64(&s.configReloads)
+}
+func (s *statsSystem) AddConfigReload() {
+	atomic.AddUint64(&s.configReloads, 1)
+}
+func (s *statsSystem) LastReload() time.Time {
+	return time.Unix(0, atomic.LoadInt64(&s.lastReloadUnixNano))
+}
+func (s *statsSystem) SetLastReload(t time.Time) {
+	atomic.StoreInt64(&s.lastReloadUnixNano, t.UnixNano())
+}
+func (s *statsSystem) AstatsLoad() time.Time {
+	return time.Unix(0, atomic.LoadInt64(&s.astatsLoadUnixNano))
+}
+func (s *statsSystem) SetAstatsLoad(t time.Time) {
+	atomic.StoreInt64(&s.astatsLoadUnixNano, t.UnixNano())
+}
+func (s *statsSystem) Version() string {
+	return s.version
+}
+
+const ATSVersion = "5.3.2" // of course, we're not really ATS. We're terrible liars.
+
+// type StatsATSJSON struct {
+// 	Server string            `json:"server"`
+// 	Remap  map[string]uint64 `json:"remap"`
+// }
+
+type StatsSystemJSON struct {
+	InterfaceName        string `json:"inf.name"`
+	InterfaceSpeed       int64  `json:"inf.speed"`
+	ProcNetDev           string `json:"proc.net.dev"`
+	ProcLoadAvg          string `json:"proc.loadavg"`
+	ConfigReloadRequests uint64 `json:"configReloadRequests"`
+	LastReloadRequest    int64  `json:"lastReloadRequest"`
+	ConfigReloads        uint64 `json:"configReloads"`
+	LastReload           int64  `json:"lastReload"`
+	AstatsLoad           int64  `json:"astatsLoad"`
+	Something            string `json:"something"`
+	Version              string `json:"application_version"`
+}
+
+type StatsJSON struct {
+	ATS    map[string]interface{} `json:"ats"`
+	System StatsSystemJSON        `json:"system"`
+}
diff --git a/grove/stat/stats_test.go b/grove/stat/stats_test.go
new file mode 100644
index 000000000..805105b45
--- /dev/null
+++ b/grove/stat/stats_test.go
@@ -0,0 +1,175 @@
+package stat
+
+/*
+   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.
+*/
+
+import (
+	"math/rand"
+	"net"
+	"testing"
+	"time"
+
+	"github.com/apache/incubator-trafficcontrol/grove/remap"
+	"github.com/apache/incubator-trafficcontrol/grove/web"
+)
+
+func StatsInc(m *web.ConnMap, num int, addrs *[]string) {
+	for i := 0; i < num; i++ {
+		c := NewFakeConn()
+		*addrs = append(*addrs, c.RemoteAddr().String())
+		m.Add(c)
+	}
+}
+
+func StatsDec(m *web.ConnMap, num int, addrs *[]string) {
+	for i := 0; i < num; i++ {
+		if len(*addrs) == 0 {
+			return
+		}
+		m.Remove((*addrs)[0])
+		*addrs = (*addrs)[1:]
+	}
+}
+
+type FakeConn struct{ Addr net.Addr }
+
+func (c FakeConn) Read(b []byte) (n int, err error)   { return 0, nil }
+func (c FakeConn) Write(b []byte) (n int, err error)  { return 0, nil }
+func (c FakeConn) Close() error                       { return nil }
+func (c FakeConn) LocalAddr() net.Addr                { return c.Addr }
+func (c FakeConn) RemoteAddr() net.Addr               { return c.Addr }
+func (c FakeConn) SetDeadline(t time.Time) error      { return nil }
+func (c FakeConn) SetReadDeadline(t time.Time) error  { return nil }
+func (c FakeConn) SetWriteDeadline(t time.Time) error { return nil }
+
+type FakeAddr struct {
+	addr    string
+	network string
+}
+
+func (a FakeAddr) Network() string { return a.network }
+func (a FakeAddr) Addr() string    { return a.addr }
+func (a FakeAddr) String() string  { return a.addr }
+
+func NewFakeConn() net.Conn {
+	s := GenGUIDStr()
+	a := FakeAddr{addr: s, network: s}
+	return FakeConn{Addr: net.Addr(&a)}
+}
+
+func GenGUIDStr() string {
+	length := 32 // 32 characters ought to be enough for anyone
+	alphabet := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_")
+	s := make([]rune, length)
+	for i := range s {
+		s[i] = alphabet[rand.Intn(len(alphabet))]
+	}
+	return string(s)
+}
+
+func TestStatsCount(t *testing.T) {
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		expected := 10
+		StatsInc(httpConns, expected, &addrs)
+		if actual := stats.Connections(); actual != uint64(expected) {
+			t.Errorf("Stats.Connections() expected %v actual %v", expected, actual)
+		}
+	}
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		expected := 10
+		StatsInc(httpsConns, expected, &addrs)
+		if actual := stats.Connections(); actual != uint64(expected) {
+			t.Errorf("Stats.Connections() expected %v actual %v", expected, actual)
+		}
+	}
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		expected := 10
+		StatsInc(httpConns, expected, &addrs)
+		StatsInc(httpsConns, expected, &addrs)
+		if actual := stats.Connections(); actual != uint64(expected)*2 {
+			t.Errorf("Stats.Connections() expected %v actual %v", expected, actual)
+		}
+	}
+
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		count := 10
+		StatsInc(httpConns, count, &addrs)
+		StatsDec(httpConns, count, &addrs)
+		if actual := stats.Connections(); actual != 0 {
+			t.Errorf("Stats.Connections() expected %v actual %v", 0, actual)
+		}
+	}
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		count := 10
+		StatsInc(httpsConns, count, &addrs)
+		StatsDec(httpsConns, count, &addrs)
+		if actual := stats.Connections(); actual != 0 {
+			t.Errorf("Stats.Connections() expected %v actual %v", 0, actual)
+		}
+	}
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		count := 10
+		StatsInc(httpConns, count, &addrs)
+		StatsInc(httpsConns, count, &addrs)
+		StatsDec(httpConns, count, &addrs)
+		if actual := stats.Connections(); actual != uint64(count) {
+			t.Errorf("Stats.Connections() expected %v actual %v", count, actual)
+		}
+	}
+
+	{
+		httpConns := web.NewConnMap()
+		httpsConns := web.NewConnMap()
+		addrs := []string{}
+		r := remap.RemapRule{RemapRuleBase: remap.RemapRuleBase{Name: "foo"}}
+		stats := New([]remap.RemapRule{r}, nil, 0, httpConns, httpsConns)
+		count := 10
+		StatsInc(httpConns, count, &addrs)
+		StatsDec(httpConns, 1, &addrs)
+		if actual := stats.Connections(); actual != uint64(count-1) {
+			t.Errorf("stats.Connections() expected %v actual %v", count-1, actual)
+		}
+	}
+
+}
diff --git a/grove/testorigin/testorigin.go b/grove/testorigin/testorigin.go
new file mode 100644
index 000000000..00b9adeb9
--- /dev/null
+++ b/grove/testorigin/testorigin.go
@@ -0,0 +1,62 @@
+package main
+
+/*
+   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.
+*/
+
+import (
+	"flag"
+	"fmt"
+	"math/rand"
+	"net/http"
+	"os"
+	"time"
+)
+
+func GetRandPage(pageLenBytes int) []byte {
+	page := make([]byte, pageLenBytes, pageLenBytes)
+	rand.Seed(time.Now().Unix())
+	rand.Read(page)
+	return page
+}
+
+func Handle(w http.ResponseWriter, r *http.Request, page []byte) {
+	fmt.Printf("%v %v %v\n", time.Now(), r.RemoteAddr, r.RequestURI)
+	// w.Header().Set("Content-Type", "application/octet-stream")
+	w.Header().Set("Content-Type", "text/html")
+	w.Write([]byte(page))
+}
+
+func main() {
+	port := flag.Int("port", -1, "The port to serve on")
+	pageBytes := flag.Int("pagebytes", -1, "The number of random bytes to serve as a page")
+	flag.Parse()
+	if *port < 0 || *pageBytes < 0 {
+		fmt.Printf("usage: testorigin -port 8080 -pagebytes 350000\n")
+		os.Exit(1)
+	}
+
+	page := GetRandPage(*pageBytes)
+
+	fmt.Printf("Serving on %d\n", *port)
+
+	handle := func(w http.ResponseWriter, r *http.Request) {
+		Handle(w, r, page)
+	}
+
+	http.HandleFunc("/", handle)
+	if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil); err != nil {
+		fmt.Printf("Error serving: %v\n", err)
+		os.Exit(1)
+	}
+}
diff --git a/grove/thread/getter.go b/grove/thread/getter.go
new file mode 100644
index 000000000..63f53e8dd
--- /dev/null
+++ b/grove/thread/getter.go
@@ -0,0 +1,87 @@
+package thread
+
+/*
+   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.
+*/
+
+import (
+	"sync"
+
+	cacheobj "github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+)
+
+type Getter interface {
+	Get(key string, actualGet func() *cacheobj.CacheObj, canUse func(*cacheobj.CacheObj) bool, reqID uint64) (*cacheobj.CacheObj, uint64)
+}
+
+type GetterResp struct {
+	CacheObj *cacheobj.CacheObj
+	GetReqID uint64
+}
+
+func NewGetter() Getter {
+	return &getter{waiters: map[string][]chan GetterResp{}}
+}
+
+// getter implements Getter, and does a fan-in so only one real request is made to the parent at any given time, and then that object is given to all concurrent requesters.
+//
+// When a request for a key with no-one currently processing it comes in, that requestor becomes the Author. Subsequent requests become Waiters.
+// The initial Author inserts a new constructed (but empty) slice into the waiters map.
+// Then, when other requests come in, they see that waiters[key] exists, and add themselves to it, and block reading from their chan.
+// Then, when the Author gets its response, it iterates over the Waiters and sends the response to all of them, at the same time (with the same lock, atomically) clearing the waiters for the next request that comes in.
+//
+// If the Author response can't be used, all Waiters make their own requests.
+// Note this assumes an uncacheable response for one request is likely uncacheable for all, and it's faster and less load on the origin if so.
+// If it's likely the author request is uncacheable, but a different waiter is cacheable for all other waiters, this will be more network, more origin load, and more work. If that's the case for you, consider creating another type that fulfills the Getter interface, and making the Getter configurable.
+type getter struct {
+	// waiters is a map of cache keys to chans for getters.
+	waiters  map[string][]chan GetterResp
+	waitersM sync.Mutex
+}
+
+func (g *getter) Get(key string, actualGet func() *cacheobj.CacheObj, canUse func(*cacheobj.CacheObj) bool, reqID uint64) (*cacheobj.CacheObj, uint64) {
+	isAuthor := false
+	// Buffered for performance, so the author can iterate over all wait chans without blocking.
+	// Note this is unused if isAuthor becomes true.
+	getChan := make(chan GetterResp, 1)
+
+	g.waitersM.Lock()
+	if _, ok := g.waiters[key]; !ok {
+		isAuthor = true
+		g.waiters[key] = []chan GetterResp{}
+	} else {
+		g.waiters[key] = append(g.waiters[key], getChan)
+	}
+	g.waitersM.Unlock()
+
+	if isAuthor {
+		obj := actualGet()
+		waitResp := GetterResp{CacheObj: obj, GetReqID: reqID}
+
+		g.waitersM.Lock()
+		for _, waitChan := range g.waiters[key] {
+			waitChan <- waitResp
+		}
+		delete(g.waiters, key)
+		g.waitersM.Unlock()
+
+		return obj, reqID
+	}
+
+	if waitResp := <-getChan; canUse(waitResp.CacheObj) {
+		return waitResp.CacheObj, waitResp.GetReqID
+	}
+
+	// if the Author response can't be used, all Waiters make their own requests
+	return actualGet(), reqID
+}
diff --git a/grove/thread/limiter.go b/grove/thread/limiter.go
new file mode 100644
index 000000000..352bd6858
--- /dev/null
+++ b/grove/thread/limiter.go
@@ -0,0 +1,93 @@
+package thread
+
+/*
+   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.
+*/
+
+import (
+	"sync"
+)
+
+type Throttler interface {
+	Throttle(f func())
+}
+
+type throttler struct {
+	c chan struct{}
+}
+
+func NewThrottler(max uint64) Throttler {
+	if max < 1 {
+		return NewNoThrottler()
+	}
+	return &throttler{c: make(chan struct{}, max)}
+}
+
+func (l *throttler) Throttle(f func()) {
+	l.c <- struct{}{}
+	f()
+	<-l.c
+}
+
+func NewThrottlers(max uint64) Throttlers {
+	return &throttlers{max: max, throttlers: map[string]Throttler{}}
+}
+
+type Throttlers interface {
+	Throttle(k string, f func())
+}
+
+// Throttlers provides a threadsafe way to map throttlers to string keys, and delete the throttler when it is no longer being used (i.e. there's nothing requesting that key).
+type throttlers struct {
+	max           uint64
+	throttlers    map[string]Throttler
+	mutex         sync.Mutex
+	checkoutCount uint64
+}
+
+func (t *throttlers) checkoutThrottler(k string) Throttler {
+	t.mutex.Lock()
+	defer t.mutex.Unlock()
+	throttler, ok := t.throttlers[k]
+	if !ok {
+		throttler = NewThrottler(t.max)
+		t.throttlers[k] = throttler
+	}
+	return throttler
+}
+
+func (t *throttlers) checkinThrottler(k string) {
+	t.mutex.Lock()
+	defer t.mutex.Unlock()
+	t.checkoutCount--
+	if t.checkoutCount == 0 {
+		delete(t.throttlers, k)
+	}
+}
+
+func (t *throttlers) Throttle(k string, f func()) {
+	throttler := t.checkoutThrottler(k)
+	throttler.Throttle(f)
+	t.checkinThrottler(k)
+}
+
+type nothrottler struct{}
+
+// NewNoThrottler creates and returns a Throttler which doesn't actually throttle, but Throttle(f) immediately calls f.
+func NewNoThrottler() Throttler {
+	return &nothrottler{}
+}
+
+func (l *nothrottler) Throttle(f func()) {
+	f()
+}
diff --git a/grove/tiercache/tiercache.go b/grove/tiercache/tiercache.go
new file mode 100644
index 000000000..418d10ad1
--- /dev/null
+++ b/grove/tiercache/tiercache.go
@@ -0,0 +1,90 @@
+package tiercache
+
+/*
+   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.
+*/
+
+import (
+	"github.com/apache/incubator-trafficcontrol/grove/cacheobj"
+	"github.com/apache/incubator-trafficcontrol/grove/icache"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-log"
+)
+
+// TierCache wraps two icache.Caches and implements icache.Cache. Adding adds to both caches. Getting tries the first cache first, and if it isn't found, it then tries the second. Thus, the first should be smaller and faster (memory) and the second should be larger and slower (disk).
+//
+// This is more suitable for more less-frequently-requested items, with a separate cache for fewer frequently-requested items.
+//
+// An alternative implementation would be to Add to the first only, and when an object is evicted from the first, then store in the second. That would be more efficient for any given frequency, but less efficient for known infrequent objects.
+type TierCache struct {
+	first  icache.Cache
+	second icache.Cache
+}
+
+// New creates a new TierCache with the given first and second caches to use.
+func New(first, second icache.Cache) *TierCache {
+	return &TierCache{first: first, second: second}
+}
+
+// Get returns the object if it's in the first cache. Else, it returns the object from the second cache. Else, false.
+func (c *TierCache) Get(key string) (*cacheobj.CacheObj, bool) {
+	log.Debugln("TierCache.Get '" + key + "' calling")
+	v, ok := c.first.Get(key)
+	log.Debugf("TierCache.Get '"+key+"' FOUND FIRST: %+v\n", ok)
+	if !ok {
+		v, ok = c.second.Get(key)
+		if ok {
+			// if it was in second but not first, add back to first (LRU behavior)
+			c.first.Add(key, v)
+		}
+		log.Debugf("TierCache.Get '"+key+"' FOUND SECOND: %+v\n", ok)
+	}
+	return v, ok
+}
+
+// Peek returns the object if it's in the first cache. Else, it returns the object from the second cache. Else, false.
+// Peek does not change the lru-ness, or the first cache
+func (c *TierCache) Peek(key string) (*cacheobj.CacheObj, bool) {
+	v, ok := c.first.Peek(key)
+	if !ok {
+		v, ok = c.second.Peek(key)
+	}
+	return v, ok
+}
+
+// Add adds to both internal caches. Returns whether either reported an eviction.
+func (c *TierCache) Add(key string, val *cacheobj.CacheObj) bool {
+	aevict := c.first.Add(key, val)
+	bevict := c.second.Add(key, val)
+	return aevict || bevict
+}
+
+// Size returns the size of the second cache. This is because, since all objects are added to both, they are presumed to have the same content, and the second is presumed to be larger.
+//
+// For example, if the first is a memory cache and the second is a disk cache, it's most useful to report the size used on disk.
+func (c *TierCache) Size() uint64 {
+	return c.second.Size()
+}
+
+func (c *TierCache) Close() {
+	c.first.Close()
+	c.second.Close()
+}
+
+// Keys returns the keys of the second tier only. The first is just an accelerator.
+func (c *TierCache) Keys() []string {
+	return c.second.Keys()
+}
+
+// Capacity returns the maximum size in bytes of the cache
+func (c *TierCache) Capacity() uint64 { return c.second.Capacity() }
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/LICENSE b/grove/vendor/code.cloudfoundry.org/bytefmt/LICENSE
new file mode 100644
index 000000000..f49a4e16e
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
\ No newline at end of file
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/NOTICE b/grove/vendor/code.cloudfoundry.org/bytefmt/NOTICE
new file mode 100644
index 000000000..8625a7f41
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/NOTICE
@@ -0,0 +1,20 @@
+Copyright (c) 2015-Present CloudFoundry.org Foundation, Inc. All Rights Reserved.
+
+This project contains software that is Copyright (c) 2013-2015 Pivotal Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+This project may include a number of subcomponents with separate
+copyright notices and license terms. Your use of these subcomponents
+is subject to the terms and conditions of each subcomponent's license,
+as noted in the LICENSE file.
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/README.md b/grove/vendor/code.cloudfoundry.org/bytefmt/README.md
new file mode 100644
index 000000000..44d287d1e
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/README.md
@@ -0,0 +1,15 @@
+bytefmt
+=======
+
+**Note**: This repository should be imported as `code.cloudfoundry.org/bytefmt`.
+
+Human-readable byte formatter.
+
+Example:
+
+```go
+bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // returns "100.5M"
+bytefmt.ByteSize(uint64(1024)) // returns "1K"
+```
+
+For documentation, please see http://godoc.org/code.cloudfoundry.org/bytefmt
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/bytes.go b/grove/vendor/code.cloudfoundry.org/bytefmt/bytes.go
new file mode 100644
index 000000000..f33bb95d5
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/bytes.go
@@ -0,0 +1,106 @@
+// Package bytefmt contains helper methods and constants for converting to and from a human-readable byte format.
+//
+//	bytefmt.ByteSize(100.5*bytefmt.MEGABYTE) // "100.5M"
+//	bytefmt.ByteSize(uint64(1024)) // "1K"
+//
+package bytefmt
+
+import (
+	"errors"
+	"fmt"
+	"regexp"
+	"strconv"
+	"strings"
+)
+
+const (
+	BYTE = 1.0 << (10 * iota)
+	KILOBYTE
+	MEGABYTE
+	GIGABYTE
+	TERABYTE
+)
+
+var (
+	bytesPattern             = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)([KMGT]i?B?|B)$`)
+	invalidByteQuantityError = errors.New("byte quantity must be a positive integer with a unit of measurement like M, MB, MiB, G, GiB, or GB")
+)
+
+// ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth.  The following units are available:
+//	T: Terabyte
+//	G: Gigabyte
+//	M: Megabyte
+//	K: Kilobyte
+//	B: Byte
+// The unit that results in the smallest number greater than or equal to 1 is always chosen.
+func ByteSize(bytes uint64) string {
+	unit := ""
+	value := float32(bytes)
+
+	switch {
+	case bytes >= TERABYTE:
+		unit = "T"
+		value = value / TERABYTE
+	case bytes >= GIGABYTE:
+		unit = "G"
+		value = value / GIGABYTE
+	case bytes >= MEGABYTE:
+		unit = "M"
+		value = value / MEGABYTE
+	case bytes >= KILOBYTE:
+		unit = "K"
+		value = value / KILOBYTE
+	case bytes >= BYTE:
+		unit = "B"
+	case bytes == 0:
+		return "0"
+	}
+
+	stringValue := fmt.Sprintf("%.1f", value)
+	stringValue = strings.TrimSuffix(stringValue, ".0")
+	return fmt.Sprintf("%s%s", stringValue, unit)
+}
+
+// ToMegabytes parses a string formatted by ByteSize as megabytes.
+func ToMegabytes(s string) (uint64, error) {
+	bytes, err := ToBytes(s)
+	if err != nil {
+		return 0, err
+	}
+
+	return bytes / MEGABYTE, nil
+}
+
+// ToBytes parses a string formatted by ByteSize as bytes. Note binary-prefixed and SI prefixed units both mean a base-2 units
+// KB = K = KiB	= 1024
+// MB = M = MiB = 1024 * K
+// GB = G = GiB = 1024 * M
+// TB = T = TiB = 1024 * G
+func ToBytes(s string) (uint64, error) {
+	parts := bytesPattern.FindStringSubmatch(strings.TrimSpace(s))
+	if len(parts) < 3 {
+		return 0, invalidByteQuantityError
+	}
+
+	value, err := strconv.ParseFloat(parts[1], 64)
+	if err != nil || value <= 0 {
+		return 0, invalidByteQuantityError
+	}
+
+	var bytes uint64
+	unit := strings.ToUpper(parts[2])
+	switch unit[:1] {
+	case "T":
+		bytes = uint64(value * TERABYTE)
+	case "G":
+		bytes = uint64(value * GIGABYTE)
+	case "M":
+		bytes = uint64(value * MEGABYTE)
+	case "K":
+		bytes = uint64(value * KILOBYTE)
+	case "B":
+		bytes = uint64(value * BYTE)
+	}
+
+	return bytes, nil
+}
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/bytes_test.go b/grove/vendor/code.cloudfoundry.org/bytefmt/bytes_test.go
new file mode 100644
index 000000000..1f2185f0c
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/bytes_test.go
@@ -0,0 +1,271 @@
+package bytefmt_test
+
+import (
+	. "code.cloudfoundry.org/bytefmt"
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("bytefmt", func() {
+
+	Context("ByteSize", func() {
+		It("Prints in the largest possible unit", func() {
+			Expect(ByteSize(10 * TERABYTE)).To(Equal("10T"))
+			Expect(ByteSize(uint64(10.5 * TERABYTE))).To(Equal("10.5T"))
+
+			Expect(ByteSize(10 * GIGABYTE)).To(Equal("10G"))
+			Expect(ByteSize(uint64(10.5 * GIGABYTE))).To(Equal("10.5G"))
+
+			Expect(ByteSize(100 * MEGABYTE)).To(Equal("100M"))
+			Expect(ByteSize(uint64(100.5 * MEGABYTE))).To(Equal("100.5M"))
+
+			Expect(ByteSize(100 * KILOBYTE)).To(Equal("100K"))
+			Expect(ByteSize(uint64(100.5 * KILOBYTE))).To(Equal("100.5K"))
+
+			Expect(ByteSize(1)).To(Equal("1B"))
+		})
+
+		It("prints '0' for zero bytes", func() {
+			Expect(ByteSize(0)).To(Equal("0"))
+		})
+	})
+
+	Context("ToMegabytes", func() {
+		It("parses byte amounts with short units (e.g. M, G)", func() {
+			var (
+				megabytes uint64
+				err       error
+			)
+
+			megabytes, err = ToMegabytes("5B")
+			Expect(megabytes).To(Equal(uint64(0)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("5K")
+			Expect(megabytes).To(Equal(uint64(0)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("5M")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("5m")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("2G")
+			Expect(megabytes).To(Equal(uint64(2 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("3T")
+			Expect(megabytes).To(Equal(uint64(3 * 1024 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("parses byte amounts with long units (e.g MB, GB)", func() {
+			var (
+				megabytes uint64
+				err       error
+			)
+
+			megabytes, err = ToMegabytes("5MB")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("5mb")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("2GB")
+			Expect(megabytes).To(Equal(uint64(2 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("3TB")
+			Expect(megabytes).To(Equal(uint64(3 * 1024 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("parses byte amounts with long binary units (e.g MiB, GiB)", func() {
+			var (
+				megabytes uint64
+				err       error
+			)
+
+			megabytes, err = ToMegabytes("5MiB")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("5mib")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("2GiB")
+			Expect(megabytes).To(Equal(uint64(2 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+
+			megabytes, err = ToMegabytes("3TiB")
+			Expect(megabytes).To(Equal(uint64(3 * 1024 * 1024)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("returns an error when the unit is missing", func() {
+			_, err := ToMegabytes("5")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+
+		It("returns an error when the unit is unrecognized", func() {
+			_, err := ToMegabytes("5MBB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+
+			_, err = ToMegabytes("5BB")
+			Expect(err).To(HaveOccurred())
+		})
+
+		It("allows whitespace before and after the value", func() {
+			megabytes, err := ToMegabytes("\t\n\r 5MB ")
+			Expect(megabytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("returns an error for negative values", func() {
+			_, err := ToMegabytes("-5MB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+
+		It("returns an error for zero values", func() {
+			_, err := ToMegabytes("0TB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+	})
+
+	Context("ToBytes", func() {
+		It("parses byte amounts with short units (e.g. M, G)", func() {
+			var (
+				bytes uint64
+				err   error
+			)
+
+			bytes, err = ToBytes("5B")
+			Expect(bytes).To(Equal(uint64(5)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("5K")
+			Expect(bytes).To(Equal(uint64(5 * KILOBYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("5M")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("5m")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("2G")
+			Expect(bytes).To(Equal(uint64(2 * GIGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("3T")
+			Expect(bytes).To(Equal(uint64(3 * TERABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("parses byte amounts that are float (e.g. 5.3KB)", func() {
+			var (
+				bytes uint64
+				err   error
+			)
+
+			bytes, err = ToBytes("13.5KB")
+			Expect(bytes).To(Equal(uint64(13824)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("4.5KB")
+			Expect(bytes).To(Equal(uint64(4608)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("parses byte amounts with long units (e.g MB, GB)", func() {
+			var (
+				bytes uint64
+				err   error
+			)
+
+			bytes, err = ToBytes("5MB")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("5mb")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("2GB")
+			Expect(bytes).To(Equal(uint64(2 * GIGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("3TB")
+			Expect(bytes).To(Equal(uint64(3 * TERABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("parses byte amounts with long binary units (e.g MiB, GiB)", func() {
+			var (
+				bytes uint64
+				err   error
+			)
+
+			bytes, err = ToBytes("5MiB")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("5mib")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("2GiB")
+			Expect(bytes).To(Equal(uint64(2 * GIGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+
+			bytes, err = ToBytes("3TiB")
+			Expect(bytes).To(Equal(uint64(3 * TERABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("returns an error when the unit is missing", func() {
+			_, err := ToBytes("5")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+
+		It("returns an error when the unit is unrecognized", func() {
+			_, err := ToBytes("5MBB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+
+			_, err = ToBytes("5BB")
+			Expect(err).To(HaveOccurred())
+		})
+
+		It("allows whitespace before and after the value", func() {
+			bytes, err := ToBytes("\t\n\r 5MB ")
+			Expect(bytes).To(Equal(uint64(5 * MEGABYTE)))
+			Expect(err).NotTo(HaveOccurred())
+		})
+
+		It("returns an error for negative values", func() {
+			_, err := ToBytes("-5MB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+
+		It("returns an error for zero values", func() {
+			_, err := ToBytes("0TB")
+			Expect(err).To(HaveOccurred())
+			Expect(err.Error()).To(ContainSubstring("unit of measurement"))
+		})
+	})
+})
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/formatters_suite_test.go b/grove/vendor/code.cloudfoundry.org/bytefmt/formatters_suite_test.go
new file mode 100644
index 000000000..64af7ca46
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/formatters_suite_test.go
@@ -0,0 +1,13 @@
+package bytefmt_test
+
+import (
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+
+	"testing"
+)
+
+func TestFormatters(t *testing.T) {
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "Bytefmt Suite")
+}
diff --git a/grove/vendor/code.cloudfoundry.org/bytefmt/package.go b/grove/vendor/code.cloudfoundry.org/bytefmt/package.go
new file mode 100644
index 000000000..03429300b
--- /dev/null
+++ b/grove/vendor/code.cloudfoundry.org/bytefmt/package.go
@@ -0,0 +1 @@
+package bytefmt // import "code.cloudfoundry.org/bytefmt"
diff --git a/grove/vendor/github.com/coreos/bbolt/LICENSE b/grove/vendor/github.com/coreos/bbolt/LICENSE
new file mode 100644
index 000000000..004e77fe5
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/LICENSE
@@ -0,0 +1,20 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Ben Johnson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/grove/vendor/github.com/coreos/bbolt/Makefile b/grove/vendor/github.com/coreos/bbolt/Makefile
new file mode 100644
index 000000000..43b94f3bd
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/Makefile
@@ -0,0 +1,30 @@
+BRANCH=`git rev-parse --abbrev-ref HEAD`
+COMMIT=`git rev-parse --short HEAD`
+GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)"
+
+default: build
+
+race:
+	@go test -v -race -test.run="TestSimulate_(100op|1000op)"
+
+fmt:
+	!(gofmt -l -s -d $(shell find . -name \*.go) | grep '[a-z]')
+
+# go get honnef.co/go/tools/simple
+gosimple:
+	gosimple ./...
+
+# go get honnef.co/go/tools/unused
+unused:
+	unused ./...
+
+# go get github.com/kisielk/errcheck
+errcheck:
+	@errcheck -ignorepkg=bytes -ignore=os:Remove github.com/coreos/bbolt
+
+test:
+	go test -timeout 20m -v -coverprofile cover.out -covermode atomic
+	# Note: gets "program not an importable package" in out of path builds
+	go test -v ./cmd/bolt
+
+.PHONY: race fmt errcheck test gosimple unused
diff --git a/grove/vendor/github.com/coreos/bbolt/README.md b/grove/vendor/github.com/coreos/bbolt/README.md
new file mode 100644
index 000000000..015f0efbe
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/README.md
@@ -0,0 +1,928 @@
+bbolt
+====
+
+[![Go Report Card](https://goreportcard.com/badge/github.com/coreos/bbolt?style=flat-square)](https://goreportcard.com/report/github.com/coreos/bbolt)
+[![Coverage](https://codecov.io/gh/coreos/bbolt/branch/master/graph/badge.svg)](https://codecov.io/gh/coreos/bbolt)
+[![Godoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://godoc.org/github.com/coreos/bbolt)
+
+bbolt is a fork of [Ben Johnson's][gh_ben] [Bolt][bolt] key/value
+store. The purpose of this fork is to provide the Go community with an active
+maintenance and development target for Bolt; the goal is improved reliability
+and stability. bbolt includes bug fixes, performance enhancements, and features
+not found in Bolt while preserving backwards compatibility with the Bolt API.
+
+Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
+[LMDB project][lmdb]. The goal of the project is to provide a simple,
+fast, and reliable database for projects that don't require a full database
+server such as Postgres or MySQL.
+
+Since Bolt is meant to be used as such a low-level piece of functionality,
+simplicity is key. The API will be small and only focus on getting values
+and setting values. That's it.
+
+[gh_ben]: https://github.com/benbjohnson
+[bolt]: https://github.com/boltdb/bolt
+[hyc_symas]: https://twitter.com/hyc_symas
+[lmdb]: http://symas.com/mdb/
+
+## Project Status
+
+Bolt is stable, the API is fixed, and the file format is fixed. Full unit
+test coverage and randomized black box testing are used to ensure database
+consistency and thread safety. Bolt is currently used in high-load production
+environments serving databases as large as 1TB. Many companies such as
+Shopify and Heroku use Bolt-backed services every day.
+
+## Table of Contents
+
+- [Getting Started](#getting-started)
+  - [Installing](#installing)
+  - [Opening a database](#opening-a-database)
+  - [Transactions](#transactions)
+    - [Read-write transactions](#read-write-transactions)
+    - [Read-only transactions](#read-only-transactions)
+    - [Batch read-write transactions](#batch-read-write-transactions)
+    - [Managing transactions manually](#managing-transactions-manually)
+  - [Using buckets](#using-buckets)
+  - [Using key/value pairs](#using-keyvalue-pairs)
+  - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
+  - [Iterating over keys](#iterating-over-keys)
+    - [Prefix scans](#prefix-scans)
+    - [Range scans](#range-scans)
+    - [ForEach()](#foreach)
+  - [Nested buckets](#nested-buckets)
+  - [Database backups](#database-backups)
+  - [Statistics](#statistics)
+  - [Read-Only Mode](#read-only-mode)
+  - [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
+- [Resources](#resources)
+- [Comparison with other databases](#comparison-with-other-databases)
+  - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
+  - [LevelDB, RocksDB](#leveldb-rocksdb)
+  - [LMDB](#lmdb)
+- [Caveats & Limitations](#caveats--limitations)
+- [Reading the Source](#reading-the-source)
+- [Other Projects Using Bolt](#other-projects-using-bolt)
+
+## Getting Started
+
+### Installing
+
+To start using Bolt, install Go and run `go get`:
+
+```sh
+$ go get github.com/coreos/bbolt/...
+```
+
+This will retrieve the library and install the `bolt` command line utility into
+your `$GOBIN` path.
+
+
+### Opening a database
+
+The top-level object in Bolt is a `DB`. It is represented as a single file on
+your disk and represents a consistent snapshot of your data.
+
+To open your database, simply use the `bolt.Open()` function:
+
+```go
+package main
+
+import (
+	"log"
+
+	bolt "github.com/coreos/bbolt"
+)
+
+func main() {
+	// Open the my.db data file in your current directory.
+	// It will be created if it doesn't exist.
+	db, err := bolt.Open("my.db", 0600, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer db.Close()
+
+	...
+}
+```
+
+Please note that Bolt obtains a file lock on the data file so multiple processes
+cannot open the same database at the same time. Opening an already open Bolt
+database will cause it to hang until the other process closes it. To prevent
+an indefinite wait you can pass a timeout option to the `Open()` function:
+
+```go
+db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
+```
+
+
+### Transactions
+
+Bolt allows only one read-write transaction at a time but allows as many
+read-only transactions as you want at a time. Each transaction has a consistent
+view of the data as it existed when the transaction started.
+
+Individual transactions and all objects created from them (e.g. buckets, keys)
+are not thread safe. To work with data in multiple goroutines you must start
+a transaction for each one or use locking to ensure only one goroutine accesses
+a transaction at a time. Creating transaction from the `DB` is thread safe.
+
+Read-only transactions and read-write transactions should not depend on one
+another and generally shouldn't be opened simultaneously in the same goroutine.
+This can cause a deadlock as the read-write transaction needs to periodically
+re-map the data file but it cannot do so while a read-only transaction is open.
+
+
+#### Read-write transactions
+
+To start a read-write transaction, you can use the `DB.Update()` function:
+
+```go
+err := db.Update(func(tx *bolt.Tx) error {
+	...
+	return nil
+})
+```
+
+Inside the closure, you have a consistent view of the database. You commit the
+transaction by returning `nil` at the end. You can also rollback the transaction
+at any point by returning an error. All database operations are allowed inside
+a read-write transaction.
+
+Always check the return error as it will report any disk failures that can cause
+your transaction to not complete. If you return an error within your closure
+it will be passed through.
+
+
+#### Read-only transactions
+
+To start a read-only transaction, you can use the `DB.View()` function:
+
+```go
+err := db.View(func(tx *bolt.Tx) error {
+	...
+	return nil
+})
+```
+
+You also get a consistent view of the database within this closure, however,
+no mutating operations are allowed within a read-only transaction. You can only
+retrieve buckets, retrieve values, and copy the database within a read-only
+transaction.
+
+
+#### Batch read-write transactions
+
+Each `DB.Update()` waits for disk to commit the writes. This overhead
+can be minimized by combining multiple updates with the `DB.Batch()`
+function:
+
+```go
+err := db.Batch(func(tx *bolt.Tx) error {
+	...
+	return nil
+})
+```
+
+Concurrent Batch calls are opportunistically combined into larger
+transactions. Batch is only useful when there are multiple goroutines
+calling it.
+
+The trade-off is that `Batch` can call the given
+function multiple times, if parts of the transaction fail. The
+function must be idempotent and side effects must take effect only
+after a successful return from `DB.Batch()`.
+
+For example: don't display messages from inside the function, instead
+set variables in the enclosing scope:
+
+```go
+var id uint64
+err := db.Batch(func(tx *bolt.Tx) error {
+	// Find last key in bucket, decode as bigendian uint64, increment
+	// by one, encode back to []byte, and add new key.
+	...
+	id = newValue
+	return nil
+})
+if err != nil {
+	return ...
+}
+fmt.Println("Allocated ID %d", id)
+```
+
+
+#### Managing transactions manually
+
+The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
+function. These helper functions will start the transaction, execute a function,
+and then safely close your transaction if an error is returned. This is the
+recommended way to use Bolt transactions.
+
+However, sometimes you may want to manually start and end your transactions.
+You can use the `DB.Begin()` function directly but **please** be sure to close
+the transaction.
+
+```go
+// Start a writable transaction.
+tx, err := db.Begin(true)
+if err != nil {
+    return err
+}
+defer tx.Rollback()
+
+// Use the transaction...
+_, err := tx.CreateBucket([]byte("MyBucket"))
+if err != nil {
+    return err
+}
+
+// Commit the transaction and check for error.
+if err := tx.Commit(); err != nil {
+    return err
+}
+```
+
+The first argument to `DB.Begin()` is a boolean stating if the transaction
+should be writable.
+
+
+### Using buckets
+
+Buckets are collections of key/value pairs within the database. All keys in a
+bucket must be unique. You can create a bucket using the `DB.CreateBucket()`
+function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+	b, err := tx.CreateBucket([]byte("MyBucket"))
+	if err != nil {
+		return fmt.Errorf("create bucket: %s", err)
+	}
+	return nil
+})
+```
+
+You can also create a bucket only if it doesn't exist by using the
+`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
+function for all your top-level buckets after you open your database so you can
+guarantee that they exist for future transactions.
+
+To delete a bucket, simply call the `Tx.DeleteBucket()` function.
+
+
+### Using key/value pairs
+
+To save a key/value pair to a bucket, use the `Bucket.Put()` function:
+
+```go
+db.Update(func(tx *bolt.Tx) error {
+	b := tx.Bucket([]byte("MyBucket"))
+	err := b.Put([]byte("answer"), []byte("42"))
+	return err
+})
+```
+
+This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
+bucket. To retrieve this value, we can use the `Bucket.Get()` function:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+	b := tx.Bucket([]byte("MyBucket"))
+	v := b.Get([]byte("answer"))
+	fmt.Printf("The answer is: %s\n", v)
+	return nil
+})
+```
+
+The `Get()` function does not return an error because its operation is
+guaranteed to work (unless there is some kind of system failure). If the key
+exists then it will return its byte slice value. If it doesn't exist then it
+will return `nil`. It's important to note that you can have a zero-length value
+set to a key which is different than the key not existing.
+
+Use the `Bucket.Delete()` function to delete a key from the bucket.
+
+Please note that values returned from `Get()` are only valid while the
+transaction is open. If you need to use a value outside of the transaction
+then you must use `copy()` to copy it to another byte slice.
+
+
+### Autoincrementing integer for the bucket
+By using the `NextSequence()` function, you can let Bolt determine a sequence
+which can be used as the unique identifier for your key/value pairs. See the
+example below.
+
+```go
+// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
+func (s *Store) CreateUser(u *User) error {
+    return s.db.Update(func(tx *bolt.Tx) error {
+        // Retrieve the users bucket.
+        // This should be created when the DB is first opened.
+        b := tx.Bucket([]byte("users"))
+
+        // Generate ID for the user.
+        // This returns an error only if the Tx is closed or not writeable.
+        // That can't happen in an Update() call so I ignore the error check.
+        id, _ := b.NextSequence()
+        u.ID = int(id)
+
+        // Marshal user data into bytes.
+        buf, err := json.Marshal(u)
+        if err != nil {
+            return err
+        }
+
+        // Persist bytes to users bucket.
+        return b.Put(itob(u.ID), buf)
+    })
+}
+
+// itob returns an 8-byte big endian representation of v.
+func itob(v int) []byte {
+    b := make([]byte, 8)
+    binary.BigEndian.PutUint64(b, uint64(v))
+    return b
+}
+
+type User struct {
+    ID int
+    ...
+}
+```
+
+### Iterating over keys
+
+Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
+iteration over these keys extremely fast. To iterate over keys we'll use a
+`Cursor`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+	// Assume bucket exists and has keys
+	b := tx.Bucket([]byte("MyBucket"))
+
+	c := b.Cursor()
+
+	for k, v := c.First(); k != nil; k, v = c.Next() {
+		fmt.Printf("key=%s, value=%s\n", k, v)
+	}
+
+	return nil
+})
+```
+
+The cursor allows you to move to a specific point in the list of keys and move
+forward or backward through the keys one at a time.
+
+The following functions are available on the cursor:
+
+```
+First()  Move to the first key.
+Last()   Move to the last key.
+Seek()   Move to a specific key.
+Next()   Move to the next key.
+Prev()   Move to the previous key.
+```
+
+Each of those functions has a return signature of `(key []byte, value []byte)`.
+When you have iterated to the end of the cursor then `Next()` will return a
+`nil` key.  You must seek to a position using `First()`, `Last()`, or `Seek()`
+before calling `Next()` or `Prev()`. If you do not seek to a position then
+these functions will return a `nil` key.
+
+During iteration, if the key is non-`nil` but the value is `nil`, that means
+the key refers to a bucket rather than a value.  Use `Bucket.Bucket()` to
+access the sub-bucket.
+
+
+#### Prefix scans
+
+To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+	// Assume bucket exists and has keys
+	c := tx.Bucket([]byte("MyBucket")).Cursor()
+
+	prefix := []byte("1234")
+	for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
+		fmt.Printf("key=%s, value=%s\n", k, v)
+	}
+
+	return nil
+})
+```
+
+#### Range scans
+
+Another common use case is scanning over a range such as a time range. If you
+use a sortable time encoding such as RFC3339 then you can query a specific
+date range like this:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+	// Assume our events bucket exists and has RFC3339 encoded time keys.
+	c := tx.Bucket([]byte("Events")).Cursor()
+
+	// Our time range spans the 90's decade.
+	min := []byte("1990-01-01T00:00:00Z")
+	max := []byte("2000-01-01T00:00:00Z")
+
+	// Iterate over the 90's.
+	for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
+		fmt.Printf("%s: %s\n", k, v)
+	}
+
+	return nil
+})
+```
+
+Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
+
+
+#### ForEach()
+
+You can also use the function `ForEach()` if you know you'll be iterating over
+all the keys in a bucket:
+
+```go
+db.View(func(tx *bolt.Tx) error {
+	// Assume bucket exists and has keys
+	b := tx.Bucket([]byte("MyBucket"))
+
+	b.ForEach(func(k, v []byte) error {
+		fmt.Printf("key=%s, value=%s\n", k, v)
+		return nil
+	})
+	return nil
+})
+```
+
+Please note that keys and values in `ForEach()` are only valid while
+the transaction is open. If you need to use a key or value outside of
+the transaction, you must use `copy()` to copy it to another byte
+slice.
+
+### Nested buckets
+
+You can also store a bucket in a key to create nested buckets. The API is the
+same as the bucket management API on the `DB` object:
+
+```go
+func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
+func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
+func (*Bucket) DeleteBucket(key []byte) error
+```
+
+Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
+
+```go
+
+// createUser creates a new user in the given account.
+func createUser(accountID int, u *User) error {
+    // Start the transaction.
+    tx, err := db.Begin(true)
+    if err != nil {
+        return err
+    }
+    defer tx.Rollback()
+
+    // Retrieve the root bucket for the account.
+    // Assume this has already been created when the account was set up.
+    root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
+
+    // Setup the users bucket.
+    bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
+    if err != nil {
+        return err
+    }
+
+    // Generate an ID for the new user.
+    userID, err := bkt.NextSequence()
+    if err != nil {
+        return err
+    }
+    u.ID = userID
+
+    // Marshal and save the encoded user.
+    if buf, err := json.Marshal(u); err != nil {
+        return err
+    } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
+        return err
+    }
+
+    // Commit the transaction.
+    if err := tx.Commit(); err != nil {
+        return err
+    }
+
+    return nil
+}
+
+```
+
+
+
+
+### Database backups
+
+Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
+function to write a consistent view of the database to a writer. If you call
+this from a read-only transaction, it will perform a hot backup and not block
+your other database reads and writes.
+
+By default, it will use a regular file handle which will utilize the operating
+system's page cache. See the [`Tx`](https://godoc.org/github.com/coreos/bbolt#Tx)
+documentation for information about optimizing for larger-than-RAM datasets.
+
+One common use case is to backup over HTTP so you can use tools like `cURL` to
+do database backups:
+
+```go
+func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
+	err := db.View(func(tx *bolt.Tx) error {
+		w.Header().Set("Content-Type", "application/octet-stream")
+		w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
+		w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
+		_, err := tx.WriteTo(w)
+		return err
+	})
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusInternalServerError)
+	}
+}
+```
+
+Then you can backup using this command:
+
+```sh
+$ curl http://localhost/backup > my.db
+```
+
+Or you can open your browser to `http://localhost/backup` and it will download
+automatically.
+
+If you want to backup to another file you can use the `Tx.CopyFile()` helper
+function.
+
+
+### Statistics
+
+The database keeps a running count of many of the internal operations it
+performs so you can better understand what's going on. By grabbing a snapshot
+of these stats at two points in time we can see what operations were performed
+in that time range.
+
+For example, we could start a goroutine to log stats every 10 seconds:
+
+```go
+go func() {
+	// Grab the initial stats.
+	prev := db.Stats()
+
+	for {
+		// Wait for 10s.
+		time.Sleep(10 * time.Second)
+
+		// Grab the current stats and diff them.
+		stats := db.Stats()
+		diff := stats.Sub(&prev)
+
+		// Encode stats to JSON and print to STDERR.
+		json.NewEncoder(os.Stderr).Encode(diff)
+
+		// Save stats for the next loop.
+		prev = stats
+	}
+}()
+```
+
+It's also useful to pipe these stats to a service such as statsd for monitoring
+or to provide an HTTP endpoint that will perform a fixed-length sample.
+
+
+### Read-Only Mode
+
+Sometimes it is useful to create a shared, read-only Bolt database. To this,
+set the `Options.ReadOnly` flag when opening your database. Read-only mode
+uses a shared lock to allow multiple processes to read from the database but
+it will block any processes from opening the database in read-write mode.
+
+```go
+db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
+if err != nil {
+	log.Fatal(err)
+}
+```
+
+### Mobile Use (iOS/Android)
+
+Bolt is able to run on mobile devices by leveraging the binding feature of the
+[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
+contain your database logic and a reference to a `*bolt.DB` with a initializing
+constructor that takes in a filepath where the database file will be stored.
+Neither Android nor iOS require extra permissions or cleanup from using this method.
+
+```go
+func NewBoltDB(filepath string) *BoltDB {
+	db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+
+	return &BoltDB{db}
+}
+
+type BoltDB struct {
+	db *bolt.DB
+	...
+}
+
+func (b *BoltDB) Path() string {
+	return b.db.Path()
+}
+
+func (b *BoltDB) Close() {
+	b.db.Close()
+}
+```
+
+Database logic should be defined as methods on this wrapper struct.
+
+To initialize this struct from the native language (both platforms now sync
+their local storage to the cloud. These snippets disable that functionality for the
+database file):
+
+#### Android
+
+```java
+String path;
+if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
+    path = getNoBackupFilesDir().getAbsolutePath();
+} else{
+    path = getFilesDir().getAbsolutePath();
+}
+Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
+```
+
+#### iOS
+
+```objc
+- (void)demo {
+    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
+                                                          NSUserDomainMask,
+                                                          YES) objectAtIndex:0];
+	GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
+	[self addSkipBackupAttributeToItemAtPath:demo.path];
+	//Some DB Logic would go here
+	[demo close];
+}
+
+- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
+{
+    NSURL* URL= [NSURL fileURLWithPath: filePathString];
+    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
+
+    NSError *error = nil;
+    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
+                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
+    if(!success){
+        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
+    }
+    return success;
+}
+
+```
+
+## Resources
+
+For more information on getting started with Bolt, check out the following articles:
+
+* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
+* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
+
+
+## Comparison with other databases
+
+### Postgres, MySQL, & other relational databases
+
+Relational databases structure data into rows and are only accessible through
+the use of SQL. This approach provides flexibility in how you store and query
+your data but also incurs overhead in parsing and planning SQL statements. Bolt
+accesses all data by a byte slice key. This makes Bolt fast to read and write
+data by key but provides no built-in support for joining values together.
+
+Most relational databases (with the exception of SQLite) are standalone servers
+that run separately from your application. This gives your systems
+flexibility to connect multiple application servers to a single database
+server but also adds overhead in serializing and transporting data over the
+network. Bolt runs as a library included in your application so all data access
+has to go through your application's process. This brings data closer to your
+application but limits multi-process access to the data.
+
+
+### LevelDB, RocksDB
+
+LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
+they are libraries bundled into the application, however, their underlying
+structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
+random writes by using a write ahead log and multi-tiered, sorted files called
+SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
+have trade-offs.
+
+If you require a high random write throughput (>10,000 w/sec) or you need to use
+spinning disks then LevelDB could be a good choice. If your application is
+read-heavy or does a lot of range scans then Bolt could be a good choice.
+
+One other important consideration is that LevelDB does not have transactions.
+It supports batch writing of key/values pairs and it supports read snapshots
+but it will not give you the ability to do a compare-and-swap operation safely.
+Bolt supports fully serializable ACID transactions.
+
+
+### LMDB
+
+Bolt was originally a port of LMDB so it is architecturally similar. Both use
+a B+tree, have ACID semantics with fully serializable transactions, and support
+lock-free MVCC using a single writer and multiple readers.
+
+The two projects have somewhat diverged. LMDB heavily focuses on raw performance
+while Bolt has focused on simplicity and ease of use. For example, LMDB allows
+several unsafe actions such as direct writes for the sake of performance. Bolt
+opts to disallow actions which can leave the database in a corrupted state. The
+only exception to this in Bolt is `DB.NoSync`.
+
+There are also a few differences in API. LMDB requires a maximum mmap size when
+opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
+automatically. LMDB overloads the getter and setter functions with multiple
+flags whereas Bolt splits these specialized cases into their own functions.
+
+
+## Caveats & Limitations
+
+It's important to pick the right tool for the job and Bolt is no exception.
+Here are a few things to note when evaluating and using Bolt:
+
+* Bolt is good for read intensive workloads. Sequential write performance is
+  also fast but random writes can be slow. You can use `DB.Batch()` or add a
+  write-ahead log to help mitigate this issue.
+
+* Bolt uses a B+tree internally so there can be a lot of random page access.
+  SSDs provide a significant performance boost over spinning disks.
+
+* Try to avoid long running read transactions. Bolt uses copy-on-write so
+  old pages cannot be reclaimed while an old transaction is using them.
+
+* Byte slices returned from Bolt are only valid during a transaction. Once the
+  transaction has been committed or rolled back then the memory they point to
+  can be reused by a new page or can be unmapped from virtual memory and you'll
+  see an `unexpected fault address` panic when accessing it.
+
+* Bolt uses an exclusive write lock on the database file so it cannot be
+  shared by multiple processes.
+
+* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
+  buckets that have random inserts will cause your database to have very poor
+  page utilization.
+
+* Use larger buckets in general. Smaller buckets causes poor page utilization
+  once they become larger than the page size (typically 4KB).
+
+* Bulk loading a lot of random writes into a new bucket can be slow as the
+  page will not split until the transaction is committed. Randomly inserting
+  more than 100,000 key/value pairs into a single new bucket in a single
+  transaction is not advised.
+
+* Bolt uses a memory-mapped file so the underlying operating system handles the
+  caching of the data. Typically, the OS will cache as much of the file as it
+  can in memory and will release memory as needed to other processes. This means
+  that Bolt can show very high memory usage when working with large databases.
+  However, this is expected and the OS will release memory as needed. Bolt can
+  handle databases much larger than the available physical RAM, provided its
+  memory-map fits in the process virtual address space. It may be problematic
+  on 32-bits systems.
+
+* The data structures in the Bolt database are memory mapped so the data file
+  will be endian specific. This means that you cannot copy a Bolt file from a
+  little endian machine to a big endian machine and have it work. For most
+  users this is not a concern since most modern CPUs are little endian.
+
+* Because of the way pages are laid out on disk, Bolt cannot truncate data files
+  and return free pages back to the disk. Instead, Bolt maintains a free list
+  of unused pages within its data file. These free pages can be reused by later
+  transactions. This works well for many use cases as databases generally tend
+  to grow. However, it's important to note that deleting large chunks of data
+  will not allow you to reclaim that space on disk.
+
+  For more information on page allocation, [see this comment][page-allocation].
+
+[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
+
+
+## Reading the Source
+
+Bolt is a relatively small code base (<5KLOC) for an embedded, serializable,
+transactional key/value database so it can be a good starting point for people
+interested in how databases work.
+
+The best places to start are the main entry points into Bolt:
+
+- `Open()` - Initializes the reference to the database. It's responsible for
+  creating the database if it doesn't exist, obtaining an exclusive lock on the
+  file, reading the meta pages, & memory-mapping the file.
+
+- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
+  value of the `writable` argument. This requires briefly obtaining the "meta"
+  lock to keep track of open transactions. Only one read-write transaction can
+  exist at a time so the "rwlock" is acquired during the life of a read-write
+  transaction.
+
+- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
+  arguments, a cursor is used to traverse the B+tree to the page and position
+  where they key & value will be written. Once the position is found, the bucket
+  materializes the underlying page and the page's parent pages into memory as
+  "nodes". These nodes are where mutations occur during read-write transactions.
+  These changes get flushed to disk during commit.
+
+- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
+  to move to the page & position of a key/value pair. During a read-only
+  transaction, the key and value data is returned as a direct reference to the
+  underlying mmap file so there's no allocation overhead. For read-write
+  transactions, this data may reference the mmap file or one of the in-memory
+  node values.
+
+- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
+  or in-memory nodes. It can seek to a specific key, move to the first or last
+  value, or it can move forward or backward. The cursor handles the movement up
+  and down the B+tree transparently to the end user.
+
+- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
+  into pages to be written to disk. Writing to disk then occurs in two phases.
+  First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
+  new meta page with an incremented transaction ID is written and another
+  `fsync()` occurs. This two phase write ensures that partially written data
+  pages are ignored in the event of a crash since the meta page pointing to them
+  is never written. Partially written meta pages are invalidated because they
+  are written with a checksum.
+
+If you have additional notes that could be helpful for others, please submit
+them via pull request.
+
+
+## Other Projects Using Bolt
+
+Below is a list of public, open source projects that use Bolt:
+
+* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
+* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
+* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
+* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
+* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
+* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
+* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
+* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
+* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
+* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
+* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
+* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
+* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
+* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
+* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
+* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
+* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
+* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
+* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
+* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
+* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
+* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
+* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
+* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
+* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
+* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
+* [stow](https://github.com/djherbis/stow) -  a persistence manager for objects
+  backed by boltdb.
+* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
+  simple tx and key scans.
+* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
+* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
+* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
+* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
+* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
+* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
+* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
+* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
+* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
+* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
+* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
+* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
+* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
+* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
+* [boltcli](https://github.com/spacewander/boltcli) - the redis-cli for boltdb with Lua script support.
+* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
+* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
+* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
+* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
+
+If you are using Bolt in a project please send a pull request to add it to the list.
diff --git a/grove/vendor/github.com/coreos/bbolt/allocate_test.go b/grove/vendor/github.com/coreos/bbolt/allocate_test.go
new file mode 100644
index 000000000..8566b4df2
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/allocate_test.go
@@ -0,0 +1,30 @@
+package bolt
+
+import (
+	"testing"
+)
+
+func TestTx_allocatePageStats(t *testing.T) {
+	f := newFreelist()
+	f.ids = []pgid{2, 3}
+
+	tx := &Tx{
+		db: &DB{
+			freelist: f,
+			pageSize: defaultPageSize,
+		},
+		meta:  &meta{},
+		pages: make(map[pgid]*page),
+	}
+
+	prePageCnt := tx.Stats().PageCount
+	allocateCnt := f.free_count()
+
+	if _, err := tx.allocate(allocateCnt); err != nil {
+		t.Fatal(err)
+	}
+
+	if tx.Stats().PageCount != prePageCnt+allocateCnt {
+		t.Errorf("Allocated %d but got %d page in stats", allocateCnt, tx.Stats().PageCount)
+	}
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/appveyor.yml b/grove/vendor/github.com/coreos/bbolt/appveyor.yml
new file mode 100644
index 000000000..6e26e941d
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/appveyor.yml
@@ -0,0 +1,18 @@
+version: "{build}"
+
+os: Windows Server 2012 R2
+
+clone_folder: c:\gopath\src\github.com\boltdb\bolt
+
+environment:
+  GOPATH: c:\gopath
+
+install:
+  - echo %PATH%
+  - echo %GOPATH%
+  - go version
+  - go env
+  - go get -v -t ./...
+
+build_script:
+  - go test -v ./...
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_386.go b/grove/vendor/github.com/coreos/bbolt/bolt_386.go
new file mode 100644
index 000000000..820d533c1
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_386.go
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_amd64.go b/grove/vendor/github.com/coreos/bbolt/bolt_amd64.go
new file mode 100644
index 000000000..98fafdb47
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_amd64.go
@@ -0,0 +1,10 @@
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_arm.go b/grove/vendor/github.com/coreos/bbolt/bolt_arm.go
new file mode 100644
index 000000000..7e5cb4b94
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_arm.go
@@ -0,0 +1,28 @@
+package bolt
+
+import "unsafe"
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned bool
+
+func init() {
+	// Simple check to see whether this arch handles unaligned load/stores
+	// correctly.
+
+	// ARM9 and older devices require load/stores to be from/to aligned
+	// addresses. If not, the lower 2 bits are cleared and that address is
+	// read in a jumbled up order.
+
+	// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html
+
+	raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11}
+	val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2))
+
+	brokenUnaligned = val != 0x11222211
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_arm64.go b/grove/vendor/github.com/coreos/bbolt/bolt_arm64.go
new file mode 100644
index 000000000..b26d84f91
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_arm64.go
@@ -0,0 +1,12 @@
+// +build arm64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_linux.go b/grove/vendor/github.com/coreos/bbolt/bolt_linux.go
new file mode 100644
index 000000000..2b6766614
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_linux.go
@@ -0,0 +1,10 @@
+package bolt
+
+import (
+	"syscall"
+)
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+	return syscall.Fdatasync(int(db.file.Fd()))
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_mips64x.go b/grove/vendor/github.com/coreos/bbolt/bolt_mips64x.go
new file mode 100644
index 000000000..134b578bd
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_mips64x.go
@@ -0,0 +1,12 @@
+// +build mips64 mips64le
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x8000000000 // 512GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_mipsx.go b/grove/vendor/github.com/coreos/bbolt/bolt_mipsx.go
new file mode 100644
index 000000000..d5ecb0597
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_mipsx.go
@@ -0,0 +1,12 @@
+// +build mips mipsle
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x40000000 // 1GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_openbsd.go b/grove/vendor/github.com/coreos/bbolt/bolt_openbsd.go
new file mode 100644
index 000000000..7058c3d73
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_openbsd.go
@@ -0,0 +1,27 @@
+package bolt
+
+import (
+	"syscall"
+	"unsafe"
+)
+
+const (
+	msAsync      = 1 << iota // perform asynchronous writes
+	msSync                   // perform synchronous writes
+	msInvalidate             // invalidate cached data
+)
+
+func msync(db *DB) error {
+	_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate)
+	if errno != 0 {
+		return errno
+	}
+	return nil
+}
+
+func fdatasync(db *DB) error {
+	if db.data != nil {
+		return msync(db)
+	}
+	return db.file.Sync()
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_ppc.go b/grove/vendor/github.com/coreos/bbolt/bolt_ppc.go
new file mode 100644
index 000000000..55cb8a72c
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_ppc.go
@@ -0,0 +1,12 @@
+// +build ppc
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0x7FFFFFFF // 2GB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0xFFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_ppc64.go b/grove/vendor/github.com/coreos/bbolt/bolt_ppc64.go
new file mode 100644
index 000000000..9331d9771
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_ppc64.go
@@ -0,0 +1,12 @@
+// +build ppc64
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_ppc64le.go b/grove/vendor/github.com/coreos/bbolt/bolt_ppc64le.go
new file mode 100644
index 000000000..8c143bc5d
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_ppc64le.go
@@ -0,0 +1,12 @@
+// +build ppc64le
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_s390x.go b/grove/vendor/github.com/coreos/bbolt/bolt_s390x.go
new file mode 100644
index 000000000..d7c39af92
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_s390x.go
@@ -0,0 +1,12 @@
+// +build s390x
+
+package bolt
+
+// maxMapSize represents the largest mmap size supported by Bolt.
+const maxMapSize = 0xFFFFFFFFFFFF // 256TB
+
+// maxAllocSize is the size used when creating array pointers.
+const maxAllocSize = 0x7FFFFFFF
+
+// Are unaligned load/stores broken on this arch?
+var brokenUnaligned = false
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_unix.go b/grove/vendor/github.com/coreos/bbolt/bolt_unix.go
new file mode 100644
index 000000000..06592a080
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_unix.go
@@ -0,0 +1,92 @@
+// +build !windows,!plan9,!solaris
+
+package bolt
+
+import (
+	"fmt"
+	"os"
+	"syscall"
+	"time"
+	"unsafe"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+	var t time.Time
+	if timeout != 0 {
+		t = time.Now()
+	}
+	fd := db.file.Fd()
+	flag := syscall.LOCK_NB
+	if exclusive {
+		flag |= syscall.LOCK_EX
+	} else {
+		flag |= syscall.LOCK_SH
+	}
+	for {
+		// Attempt to obtain an exclusive lock.
+		err := syscall.Flock(int(fd), flag)
+		if err == nil {
+			return nil
+		} else if err != syscall.EWOULDBLOCK {
+			return err
+		}
+
+		// If we timed out then return an error.
+		if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout {
+			return ErrTimeout
+		}
+
+		// Wait for a bit and try again.
+		time.Sleep(flockRetryTimeout)
+	}
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+	return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+	// Map the data file to memory.
+	b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+	if err != nil {
+		return err
+	}
+
+	// Advise the kernel that the mmap is accessed randomly.
+	if err := madvise(b, syscall.MADV_RANDOM); err != nil {
+		return fmt.Errorf("madvise: %s", err)
+	}
+
+	// Save the original byte slice and convert to a byte array pointer.
+	db.dataref = b
+	db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+	db.datasz = sz
+	return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+	// Ignore the unmap if we have no mapped data.
+	if db.dataref == nil {
+		return nil
+	}
+
+	// Unmap using the original byte slice.
+	err := syscall.Munmap(db.dataref)
+	db.dataref = nil
+	db.data = nil
+	db.datasz = 0
+	return err
+}
+
+// NOTE: This function is copied from stdlib because it is not available on darwin.
+func madvise(b []byte, advice int) (err error) {
+	_, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
+	if e1 != 0 {
+		err = e1
+	}
+	return
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go b/grove/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go
new file mode 100644
index 000000000..fd8335ecc
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_unix_solaris.go
@@ -0,0 +1,89 @@
+package bolt
+
+import (
+	"fmt"
+	"os"
+	"syscall"
+	"time"
+	"unsafe"
+
+	"golang.org/x/sys/unix"
+)
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+	var t time.Time
+	if timeout != 0 {
+		t = time.Now()
+	}
+	fd := db.file.Fd()
+	var lockType int16
+	if exclusive {
+		lockType = syscall.F_WRLCK
+	} else {
+		lockType = syscall.F_RDLCK
+	}
+	for {
+		// Attempt to obtain an exclusive lock.
+		lock := syscall.Flock_t{Type: lockType}
+		err := syscall.FcntlFlock(fd, syscall.F_SETLK, &lock)
+		if err == nil {
+			return nil
+		} else if err != syscall.EAGAIN {
+			return err
+		}
+
+		// If we timed out then return an error.
+		if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout {
+			return ErrTimeout
+		}
+
+		// Wait for a bit and try again.
+		time.Sleep(flockRetryTimeout)
+	}
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+	var lock syscall.Flock_t
+	lock.Start = 0
+	lock.Len = 0
+	lock.Type = syscall.F_UNLCK
+	lock.Whence = 0
+	return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
+}
+
+// mmap memory maps a DB's data file.
+func mmap(db *DB, sz int) error {
+	// Map the data file to memory.
+	b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
+	if err != nil {
+		return err
+	}
+
+	// Advise the kernel that the mmap is accessed randomly.
+	if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
+		return fmt.Errorf("madvise: %s", err)
+	}
+
+	// Save the original byte slice and convert to a byte array pointer.
+	db.dataref = b
+	db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
+	db.datasz = sz
+	return nil
+}
+
+// munmap unmaps a DB's data file from memory.
+func munmap(db *DB) error {
+	// Ignore the unmap if we have no mapped data.
+	if db.dataref == nil {
+		return nil
+	}
+
+	// Unmap using the original byte slice.
+	err := unix.Munmap(db.dataref)
+	db.dataref = nil
+	db.data = nil
+	db.datasz = 0
+	return err
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bolt_windows.go b/grove/vendor/github.com/coreos/bbolt/bolt_windows.go
new file mode 100644
index 000000000..ca6f9a11c
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bolt_windows.go
@@ -0,0 +1,145 @@
+package bolt
+
+import (
+	"fmt"
+	"os"
+	"syscall"
+	"time"
+	"unsafe"
+)
+
+// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1
+var (
+	modkernel32      = syscall.NewLazyDLL("kernel32.dll")
+	procLockFileEx   = modkernel32.NewProc("LockFileEx")
+	procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
+)
+
+const (
+	lockExt = ".lock"
+
+	// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
+	flagLockExclusive       = 2
+	flagLockFailImmediately = 1
+
+	// see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
+	errLockViolation syscall.Errno = 0x21
+)
+
+func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+	r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
+	if r == 0 {
+		return err
+	}
+	return nil
+}
+
+func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
+	r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0)
+	if r == 0 {
+		return err
+	}
+	return nil
+}
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+	return db.file.Sync()
+}
+
+// flock acquires an advisory lock on a file descriptor.
+func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
+	// Create a separate lock file on windows because a process
+	// cannot share an exclusive lock on the same file. This is
+	// needed during Tx.WriteTo().
+	f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode)
+	if err != nil {
+		return err
+	}
+	db.lockfile = f
+
+	var t time.Time
+	if timeout != 0 {
+		t = time.Now()
+	}
+	fd := f.Fd()
+	var flag uint32 = flagLockFailImmediately
+	if exclusive {
+		flag |= flagLockExclusive
+	}
+	for {
+		// Attempt to obtain an exclusive lock.
+		err := lockFileEx(syscall.Handle(fd), flag, 0, 1, 0, &syscall.Overlapped{})
+		if err == nil {
+			return nil
+		} else if err != errLockViolation {
+			return err
+		}
+
+		// If we timed oumercit then return an error.
+		if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout {
+			return ErrTimeout
+		}
+
+		// Wait for a bit and try again.
+		time.Sleep(flockRetryTimeout)
+	}
+}
+
+// funlock releases an advisory lock on a file descriptor.
+func funlock(db *DB) error {
+	err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{})
+	db.lockfile.Close()
+	os.Remove(db.path + lockExt)
+	return err
+}
+
+// mmap memory maps a DB's data file.
+// Based on: https://github.com/edsrzf/mmap-go
+func mmap(db *DB, sz int) error {
+	if !db.readOnly {
+		// Truncate the database to the size of the mmap.
+		if err := db.file.Truncate(int64(sz)); err != nil {
+			return fmt.Errorf("truncate: %s", err)
+		}
+	}
+
+	// Open a file mapping handle.
+	sizelo := uint32(sz >> 32)
+	sizehi := uint32(sz) & 0xffffffff
+	h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
+	if h == 0 {
+		return os.NewSyscallError("CreateFileMapping", errno)
+	}
+
+	// Create the memory map.
+	addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
+	if addr == 0 {
+		return os.NewSyscallError("MapViewOfFile", errno)
+	}
+
+	// Close mapping handle.
+	if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
+		return os.NewSyscallError("CloseHandle", err)
+	}
+
+	// Convert to a byte array.
+	db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr)))
+	db.datasz = sz
+
+	return nil
+}
+
+// munmap unmaps a pointer from a file.
+// Based on: https://github.com/edsrzf/mmap-go
+func munmap(db *DB) error {
+	if db.data == nil {
+		return nil
+	}
+
+	addr := (uintptr)(unsafe.Pointer(&db.data[0]))
+	if err := syscall.UnmapViewOfFile(addr); err != nil {
+		return os.NewSyscallError("UnmapViewOfFile", err)
+	}
+	return nil
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/boltsync_unix.go b/grove/vendor/github.com/coreos/bbolt/boltsync_unix.go
new file mode 100644
index 000000000..f50442523
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/boltsync_unix.go
@@ -0,0 +1,8 @@
+// +build !windows,!plan9,!linux,!openbsd
+
+package bolt
+
+// fdatasync flushes written data to a file descriptor.
+func fdatasync(db *DB) error {
+	return db.file.Sync()
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bucket.go b/grove/vendor/github.com/coreos/bbolt/bucket.go
new file mode 100644
index 000000000..44db88b8a
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bucket.go
@@ -0,0 +1,775 @@
+package bolt
+
+import (
+	"bytes"
+	"fmt"
+	"unsafe"
+)
+
+const (
+	// MaxKeySize is the maximum length of a key, in bytes.
+	MaxKeySize = 32768
+
+	// MaxValueSize is the maximum length of a value, in bytes.
+	MaxValueSize = (1 << 31) - 2
+)
+
+const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
+
+const (
+	minFillPercent = 0.1
+	maxFillPercent = 1.0
+)
+
+// DefaultFillPercent is the percentage that split pages are filled.
+// This value can be changed by setting Bucket.FillPercent.
+const DefaultFillPercent = 0.5
+
+// Bucket represents a collection of key/value pairs inside the database.
+type Bucket struct {
+	*bucket
+	tx       *Tx                // the associated transaction
+	buckets  map[string]*Bucket // subbucket cache
+	page     *page              // inline page reference
+	rootNode *node              // materialized node for the root page.
+	nodes    map[pgid]*node     // node cache
+
+	// Sets the threshold for filling nodes when they split. By default,
+	// the bucket will fill to 50% but it can be useful to increase this
+	// amount if you know that your write workloads are mostly append-only.
+	//
+	// This is non-persisted across transactions so it must be set in every Tx.
+	FillPercent float64
+}
+
+// bucket represents the on-file representation of a bucket.
+// This is stored as the "value" of a bucket key. If the bucket is small enough,
+// then its root page can be stored inline in the "value", after the bucket
+// header. In the case of inline buckets, the "root" will be 0.
+type bucket struct {
+	root     pgid   // page id of the bucket's root-level page
+	sequence uint64 // monotonically incrementing, used by NextSequence()
+}
+
+// newBucket returns a new bucket associated with a transaction.
+func newBucket(tx *Tx) Bucket {
+	var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
+	if tx.writable {
+		b.buckets = make(map[string]*Bucket)
+		b.nodes = make(map[pgid]*node)
+	}
+	return b
+}
+
+// Tx returns the tx of the bucket.
+func (b *Bucket) Tx() *Tx {
+	return b.tx
+}
+
+// Root returns the root of the bucket.
+func (b *Bucket) Root() pgid {
+	return b.root
+}
+
+// Writable returns whether the bucket is writable.
+func (b *Bucket) Writable() bool {
+	return b.tx.writable
+}
+
+// Cursor creates a cursor associated with the bucket.
+// The cursor is only valid as long as the transaction is open.
+// Do not use a cursor after the transaction is closed.
+func (b *Bucket) Cursor() *Cursor {
+	// Update transaction statistics.
+	b.tx.stats.CursorCount++
+
+	// Allocate and return a cursor.
+	return &Cursor{
+		bucket: b,
+		stack:  make([]elemRef, 0),
+	}
+}
+
+// Bucket retrieves a nested bucket by name.
+// Returns nil if the bucket does not exist.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) Bucket(name []byte) *Bucket {
+	if b.buckets != nil {
+		if child := b.buckets[string(name)]; child != nil {
+			return child
+		}
+	}
+
+	// Move cursor to key.
+	c := b.Cursor()
+	k, v, flags := c.seek(name)
+
+	// Return nil if the key doesn't exist or it is not a bucket.
+	if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
+		return nil
+	}
+
+	// Otherwise create a bucket and cache it.
+	var child = b.openBucket(v)
+	if b.buckets != nil {
+		b.buckets[string(name)] = child
+	}
+
+	return child
+}
+
+// Helper method that re-interprets a sub-bucket value
+// from a parent into a Bucket
+func (b *Bucket) openBucket(value []byte) *Bucket {
+	var child = newBucket(b.tx)
+
+	// If unaligned load/stores are broken on this arch and value is
+	// unaligned simply clone to an aligned byte array.
+	unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
+
+	if unaligned {
+		value = cloneBytes(value)
+	}
+
+	// If this is a writable transaction then we need to copy the bucket entry.
+	// Read-only transactions can point directly at the mmap entry.
+	if b.tx.writable && !unaligned {
+		child.bucket = &bucket{}
+		*child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
+	} else {
+		child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
+	}
+
+	// Save a reference to the inline page if the bucket is inline.
+	if child.root == 0 {
+		child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+	}
+
+	return &child
+}
+
+// CreateBucket creates a new bucket at the given key and returns the new bucket.
+// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
+	if b.tx.db == nil {
+		return nil, ErrTxClosed
+	} else if !b.tx.writable {
+		return nil, ErrTxNotWritable
+	} else if len(key) == 0 {
+		return nil, ErrBucketNameRequired
+	}
+
+	// Move cursor to correct position.
+	c := b.Cursor()
+	k, _, flags := c.seek(key)
+
+	// Return an error if there is an existing key.
+	if bytes.Equal(key, k) {
+		if (flags & bucketLeafFlag) != 0 {
+			return nil, ErrBucketExists
+		}
+		return nil, ErrIncompatibleValue
+	}
+
+	// Create empty, inline bucket.
+	var bucket = Bucket{
+		bucket:      &bucket{},
+		rootNode:    &node{isLeaf: true},
+		FillPercent: DefaultFillPercent,
+	}
+	var value = bucket.write()
+
+	// Insert into node.
+	key = cloneBytes(key)
+	c.node().put(key, key, value, 0, bucketLeafFlag)
+
+	// Since subbuckets are not allowed on inline buckets, we need to
+	// dereference the inline page, if it exists. This will cause the bucket
+	// to be treated as a regular, non-inline bucket for the rest of the tx.
+	b.page = nil
+
+	return b.Bucket(key), nil
+}
+
+// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
+// Returns an error if the bucket name is blank, or if the bucket name is too long.
+// The bucket instance is only valid for the lifetime of the transaction.
+func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
+	child, err := b.CreateBucket(key)
+	if err == ErrBucketExists {
+		return b.Bucket(key), nil
+	} else if err != nil {
+		return nil, err
+	}
+	return child, nil
+}
+
+// DeleteBucket deletes a bucket at the given key.
+// Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
+func (b *Bucket) DeleteBucket(key []byte) error {
+	if b.tx.db == nil {
+		return ErrTxClosed
+	} else if !b.Writable() {
+		return ErrTxNotWritable
+	}
+
+	// Move cursor to correct position.
+	c := b.Cursor()
+	k, _, flags := c.seek(key)
+
+	// Return an error if bucket doesn't exist or is not a bucket.
+	if !bytes.Equal(key, k) {
+		return ErrBucketNotFound
+	} else if (flags & bucketLeafFlag) == 0 {
+		return ErrIncompatibleValue
+	}
+
+	// Recursively delete all child buckets.
+	child := b.Bucket(key)
+	err := child.ForEach(func(k, v []byte) error {
+		if v == nil {
+			if err := child.DeleteBucket(k); err != nil {
+				return fmt.Errorf("delete bucket: %s", err)
+			}
+		}
+		return nil
+	})
+	if err != nil {
+		return err
+	}
+
+	// Remove cached copy.
+	delete(b.buckets, string(key))
+
+	// Release all bucket pages to freelist.
+	child.nodes = nil
+	child.rootNode = nil
+	child.free()
+
+	// Delete the node if we have a matching key.
+	c.node().del(key)
+
+	return nil
+}
+
+// Get retrieves the value for a key in the bucket.
+// Returns a nil value if the key does not exist or if the key is a nested bucket.
+// The returned value is only valid for the life of the transaction.
+func (b *Bucket) Get(key []byte) []byte {
+	k, v, flags := b.Cursor().seek(key)
+
+	// Return nil if this is a bucket.
+	if (flags & bucketLeafFlag) != 0 {
+		return nil
+	}
+
+	// If our target node isn't the same key as what's passed in then return nil.
+	if !bytes.Equal(key, k) {
+		return nil
+	}
+	return v
+}
+
+// Put sets the value for a key in the bucket.
+// If the key exist then its previous value will be overwritten.
+// Supplied value must remain valid for the life of the transaction.
+// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
+func (b *Bucket) Put(key []byte, value []byte) error {
+	if b.tx.db == nil {
+		return ErrTxClosed
+	} else if !b.Writable() {
+		return ErrTxNotWritable
+	} else if len(key) == 0 {
+		return ErrKeyRequired
+	} else if len(key) > MaxKeySize {
+		return ErrKeyTooLarge
+	} else if int64(len(value)) > MaxValueSize {
+		return ErrValueTooLarge
+	}
+
+	// Move cursor to correct position.
+	c := b.Cursor()
+	k, _, flags := c.seek(key)
+
+	// Return an error if there is an existing key with a bucket value.
+	if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
+		return ErrIncompatibleValue
+	}
+
+	// Insert into node.
+	key = cloneBytes(key)
+	c.node().put(key, key, value, 0, 0)
+
+	return nil
+}
+
+// Delete removes a key from the bucket.
+// If the key does not exist then nothing is done and a nil error is returned.
+// Returns an error if the bucket was created from a read-only transaction.
+func (b *Bucket) Delete(key []byte) error {
+	if b.tx.db == nil {
+		return ErrTxClosed
+	} else if !b.Writable() {
+		return ErrTxNotWritable
+	}
+
+	// Move cursor to correct position.
+	c := b.Cursor()
+	k, _, flags := c.seek(key)
+
+	// Return nil if the key doesn't exist.
+	if !bytes.Equal(key, k) {
+		return nil
+	}
+
+	// Return an error if there is already existing bucket value.
+	if (flags & bucketLeafFlag) != 0 {
+		return ErrIncompatibleValue
+	}
+
+	// Delete the node if we have a matching key.
+	c.node().del(key)
+
+	return nil
+}
+
+// Sequence returns the current integer for the bucket without incrementing it.
+func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
+
+// SetSequence updates the sequence number for the bucket.
+func (b *Bucket) SetSequence(v uint64) error {
+	if b.tx.db == nil {
+		return ErrTxClosed
+	} else if !b.Writable() {
+		return ErrTxNotWritable
+	}
+
+	// Materialize the root node if it hasn't been already so that the
+	// bucket will be saved during commit.
+	if b.rootNode == nil {
+		_ = b.node(b.root, nil)
+	}
+
+	// Increment and return the sequence.
+	b.bucket.sequence = v
+	return nil
+}
+
+// NextSequence returns an autoincrementing integer for the bucket.
+func (b *Bucket) NextSequence() (uint64, error) {
+	if b.tx.db == nil {
+		return 0, ErrTxClosed
+	} else if !b.Writable() {
+		return 0, ErrTxNotWritable
+	}
+
+	// Materialize the root node if it hasn't been already so that the
+	// bucket will be saved during commit.
+	if b.rootNode == nil {
+		_ = b.node(b.root, nil)
+	}
+
+	// Increment and return the sequence.
+	b.bucket.sequence++
+	return b.bucket.sequence, nil
+}
+
+// ForEach executes a function for each key/value pair in a bucket.
+// If the provided function returns an error then the iteration is stopped and
+// the error is returned to the caller. The provided function must not modify
+// the bucket; this will result in undefined behavior.
+func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
+	if b.tx.db == nil {
+		return ErrTxClosed
+	}
+	c := b.Cursor()
+	for k, v := c.First(); k != nil; k, v = c.Next() {
+		if err := fn(k, v); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// Stat returns stats on a bucket.
+func (b *Bucket) Stats() BucketStats {
+	var s, subStats BucketStats
+	pageSize := b.tx.db.pageSize
+	s.BucketN += 1
+	if b.root == 0 {
+		s.InlineBucketN += 1
+	}
+	b.forEachPage(func(p *page, depth int) {
+		if (p.flags & leafPageFlag) != 0 {
+			s.KeyN += int(p.count)
+
+			// used totals the used bytes for the page
+			used := pageHeaderSize
+
+			if p.count != 0 {
+				// If page has any elements, add all element headers.
+				used += leafPageElementSize * int(p.count-1)
+
+				// Add all element key, value sizes.
+				// The computation takes advantage of the fact that the position
+				// of the last element's key/value equals to the total of the sizes
+				// of all previous elements' keys and values.
+				// It also includes the last element's header.
+				lastElement := p.leafPageElement(p.count - 1)
+				used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
+			}
+
+			if b.root == 0 {
+				// For inlined bucket just update the inline stats
+				s.InlineBucketInuse += used
+			} else {
+				// For non-inlined bucket update all the leaf stats
+				s.LeafPageN++
+				s.LeafInuse += used
+				s.LeafOverflowN += int(p.overflow)
+
+				// Collect stats from sub-buckets.
+				// Do that by iterating over all element headers
+				// looking for the ones with the bucketLeafFlag.
+				for i := uint16(0); i < p.count; i++ {
+					e := p.leafPageElement(i)
+					if (e.flags & bucketLeafFlag) != 0 {
+						// For any bucket element, open the element value
+						// and recursively call Stats on the contained bucket.
+						subStats.Add(b.openBucket(e.value()).Stats())
+					}
+				}
+			}
+		} else if (p.flags & branchPageFlag) != 0 {
+			s.BranchPageN++
+			lastElement := p.branchPageElement(p.count - 1)
+
+			// used totals the used bytes for the page
+			// Add header and all element headers.
+			used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
+
+			// Add size of all keys and values.
+			// Again, use the fact that last element's position equals to
+			// the total of key, value sizes of all previous elements.
+			used += int(lastElement.pos + lastElement.ksize)
+			s.BranchInuse += used
+			s.BranchOverflowN += int(p.overflow)
+		}
+
+		// Keep track of maximum page depth.
+		if depth+1 > s.Depth {
+			s.Depth = (depth + 1)
+		}
+	})
+
+	// Alloc stats can be computed from page counts and pageSize.
+	s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
+	s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
+
+	// Add the max depth of sub-buckets to get total nested depth.
+	s.Depth += subStats.Depth
+	// Add the stats for all sub-buckets
+	s.Add(subStats)
+	return s
+}
+
+// forEachPage iterates over every page in a bucket, including inline pages.
+func (b *Bucket) forEachPage(fn func(*page, int)) {
+	// If we have an inline page then just use that.
+	if b.page != nil {
+		fn(b.page, 0)
+		return
+	}
+
+	// Otherwise traverse the page hierarchy.
+	b.tx.forEachPage(b.root, 0, fn)
+}
+
+// forEachPageNode iterates over every page (or node) in a bucket.
+// This also includes inline pages.
+func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
+	// If we have an inline page or root node then just use that.
+	if b.page != nil {
+		fn(b.page, nil, 0)
+		return
+	}
+	b._forEachPageNode(b.root, 0, fn)
+}
+
+func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
+	var p, n = b.pageNode(pgid)
+
+	// Execute function.
+	fn(p, n, depth)
+
+	// Recursively loop over children.
+	if p != nil {
+		if (p.flags & branchPageFlag) != 0 {
+			for i := 0; i < int(p.count); i++ {
+				elem := p.branchPageElement(uint16(i))
+				b._forEachPageNode(elem.pgid, depth+1, fn)
+			}
+		}
+	} else {
+		if !n.isLeaf {
+			for _, inode := range n.inodes {
+				b._forEachPageNode(inode.pgid, depth+1, fn)
+			}
+		}
+	}
+}
+
+// spill writes all the nodes for this bucket to dirty pages.
+func (b *Bucket) spill() error {
+	// Spill all child buckets first.
+	for name, child := range b.buckets {
+		// If the child bucket is small enough and it has no child buckets then
+		// write it inline into the parent bucket's page. Otherwise spill it
+		// like a normal bucket and make the parent value a pointer to the page.
+		var value []byte
+		if child.inlineable() {
+			child.free()
+			value = child.write()
+		} else {
+			if err := child.spill(); err != nil {
+				return err
+			}
+
+			// Update the child bucket header in this bucket.
+			value = make([]byte, unsafe.Sizeof(bucket{}))
+			var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+			*bucket = *child.bucket
+		}
+
+		// Skip writing the bucket if there are no materialized nodes.
+		if child.rootNode == nil {
+			continue
+		}
+
+		// Update parent node.
+		var c = b.Cursor()
+		k, _, flags := c.seek([]byte(name))
+		if !bytes.Equal([]byte(name), k) {
+			panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
+		}
+		if flags&bucketLeafFlag == 0 {
+			panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
+		}
+		c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
+	}
+
+	// Ignore if there's not a materialized root node.
+	if b.rootNode == nil {
+		return nil
+	}
+
+	// Spill nodes.
+	if err := b.rootNode.spill(); err != nil {
+		return err
+	}
+	b.rootNode = b.rootNode.root()
+
+	// Update the root node for this bucket.
+	if b.rootNode.pgid >= b.tx.meta.pgid {
+		panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
+	}
+	b.root = b.rootNode.pgid
+
+	return nil
+}
+
+// inlineable returns true if a bucket is small enough to be written inline
+// and if it contains no subbuckets. Otherwise returns false.
+func (b *Bucket) inlineable() bool {
+	var n = b.rootNode
+
+	// Bucket must only contain a single leaf node.
+	if n == nil || !n.isLeaf {
+		return false
+	}
+
+	// Bucket is not inlineable if it contains subbuckets or if it goes beyond
+	// our threshold for inline bucket size.
+	var size = pageHeaderSize
+	for _, inode := range n.inodes {
+		size += leafPageElementSize + len(inode.key) + len(inode.value)
+
+		if inode.flags&bucketLeafFlag != 0 {
+			return false
+		} else if size > b.maxInlineBucketSize() {
+			return false
+		}
+	}
+
+	return true
+}
+
+// Returns the maximum total size of a bucket to make it a candidate for inlining.
+func (b *Bucket) maxInlineBucketSize() int {
+	return b.tx.db.pageSize / 4
+}
+
+// write allocates and writes a bucket to a byte slice.
+func (b *Bucket) write() []byte {
+	// Allocate the appropriate size.
+	var n = b.rootNode
+	var value = make([]byte, bucketHeaderSize+n.size())
+
+	// Write a bucket header.
+	var bucket = (*bucket)(unsafe.Pointer(&value[0]))
+	*bucket = *b.bucket
+
+	// Convert byte slice to a fake page and write the root node.
+	var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
+	n.write(p)
+
+	return value
+}
+
+// rebalance attempts to balance all nodes.
+func (b *Bucket) rebalance() {
+	for _, n := range b.nodes {
+		n.rebalance()
+	}
+	for _, child := range b.buckets {
+		child.rebalance()
+	}
+}
+
+// node creates a node from a page and associates it with a given parent.
+func (b *Bucket) node(pgid pgid, parent *node) *node {
+	_assert(b.nodes != nil, "nodes map expected")
+
+	// Retrieve node if it's already been created.
+	if n := b.nodes[pgid]; n != nil {
+		return n
+	}
+
+	// Otherwise create a node and cache it.
+	n := &node{bucket: b, parent: parent}
+	if parent == nil {
+		b.rootNode = n
+	} else {
+		parent.children = append(parent.children, n)
+	}
+
+	// Use the inline page if this is an inline bucket.
+	var p = b.page
+	if p == nil {
+		p = b.tx.page(pgid)
+	}
+
+	// Read the page into the node and cache it.
+	n.read(p)
+	b.nodes[pgid] = n
+
+	// Update statistics.
+	b.tx.stats.NodeCount++
+
+	return n
+}
+
+// free recursively frees all pages in the bucket.
+func (b *Bucket) free() {
+	if b.root == 0 {
+		return
+	}
+
+	var tx = b.tx
+	b.forEachPageNode(func(p *page, n *node, _ int) {
+		if p != nil {
+			tx.db.freelist.free(tx.meta.txid, p)
+		} else {
+			n.free()
+		}
+	})
+	b.root = 0
+}
+
+// dereference removes all references to the old mmap.
+func (b *Bucket) dereference() {
+	if b.rootNode != nil {
+		b.rootNode.root().dereference()
+	}
+
+	for _, child := range b.buckets {
+		child.dereference()
+	}
+}
+
+// pageNode returns the in-memory node, if it exists.
+// Otherwise returns the underlying page.
+func (b *Bucket) pageNode(id pgid) (*page, *node) {
+	// Inline buckets have a fake page embedded in their value so treat them
+	// differently. We'll return the rootNode (if available) or the fake page.
+	if b.root == 0 {
+		if id != 0 {
+			panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
+		}
+		if b.rootNode != nil {
+			return nil, b.rootNode
+		}
+		return b.page, nil
+	}
+
+	// Check the node cache for non-inline buckets.
+	if b.nodes != nil {
+		if n := b.nodes[id]; n != nil {
+			return nil, n
+		}
+	}
+
+	// Finally lookup the page from the transaction if no node is materialized.
+	return b.tx.page(id), nil
+}
+
+// BucketStats records statistics about resources used by a bucket.
+type BucketStats struct {
+	// Page count statistics.
+	BranchPageN     int // number of logical branch pages
+	BranchOverflowN int // number of physical branch overflow pages
+	LeafPageN       int // number of logical leaf pages
+	LeafOverflowN   int // number of physical leaf overflow pages
+
+	// Tree statistics.
+	KeyN  int // number of keys/value pairs
+	Depth int // number of levels in B+tree
+
+	// Page size utilization.
+	BranchAlloc int // bytes allocated for physical branch pages
+	BranchInuse int // bytes actually used for branch data
+	LeafAlloc   int // bytes allocated for physical leaf pages
+	LeafInuse   int // bytes actually used for leaf data
+
+	// Bucket statistics
+	BucketN           int // total number of buckets including the top bucket
+	InlineBucketN     int // total number on inlined buckets
+	InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
+}
+
+func (s *BucketStats) Add(other BucketStats) {
+	s.BranchPageN += other.BranchPageN
+	s.BranchOverflowN += other.BranchOverflowN
+	s.LeafPageN += other.LeafPageN
+	s.LeafOverflowN += other.LeafOverflowN
+	s.KeyN += other.KeyN
+	if s.Depth < other.Depth {
+		s.Depth = other.Depth
+	}
+	s.BranchAlloc += other.BranchAlloc
+	s.BranchInuse += other.BranchInuse
+	s.LeafAlloc += other.LeafAlloc
+	s.LeafInuse += other.LeafInuse
+
+	s.BucketN += other.BucketN
+	s.InlineBucketN += other.InlineBucketN
+	s.InlineBucketInuse += other.InlineBucketInuse
+}
+
+// cloneBytes returns a copy of a given slice.
+func cloneBytes(v []byte) []byte {
+	var clone = make([]byte, len(v))
+	copy(clone, v)
+	return clone
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/bucket_test.go b/grove/vendor/github.com/coreos/bbolt/bucket_test.go
new file mode 100644
index 000000000..b7ce32c13
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/bucket_test.go
@@ -0,0 +1,1959 @@
+package bolt_test
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"log"
+	"math/rand"
+	"os"
+	"strconv"
+	"strings"
+	"testing"
+	"testing/quick"
+
+	"github.com/coreos/bbolt"
+)
+
+// Ensure that a bucket that gets a non-existent key returns nil.
+func TestBucket_Get_NonExistent(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if v := b.Get([]byte("foo")); v != nil {
+			t.Fatal("expected nil value")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can read a value that is not flushed yet.
+func TestBucket_Get_FromNode(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if v := b.Get([]byte("foo")); !bytes.Equal(v, []byte("bar")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket retrieved via Get() returns a nil.
+func TestBucket_Get_IncompatibleValue(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		_, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+
+		if tx.Bucket([]byte("widgets")).Get([]byte("foo")) != nil {
+			t.Fatal("expected nil value")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a slice returned from a bucket has a capacity equal to its length.
+// This also allows slices to be appended to since it will require a realloc by Go.
+//
+// https://github.com/boltdb/bolt/issues/544
+func TestBucket_Get_Capacity(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Write key to a bucket.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("bucket"))
+		if err != nil {
+			return err
+		}
+		return b.Put([]byte("key"), []byte("val"))
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Retrieve value and attempt to append to it.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		k, v := tx.Bucket([]byte("bucket")).Cursor().First()
+
+		// Verify capacity.
+		if len(k) != cap(k) {
+			t.Fatalf("unexpected key slice capacity: %d", cap(k))
+		} else if len(v) != cap(v) {
+			t.Fatalf("unexpected value slice capacity: %d", cap(v))
+		}
+
+		// Ensure slice can be appended to without a segfault.
+		k = append(k, []byte("123")...)
+		v = append(v, []byte("123")...)
+		_, _ = k, v // to pass ineffassign
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can write a key/value.
+func TestBucket_Put(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+
+		v := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
+		if !bytes.Equal([]byte("bar"), v) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can rewrite a key in the same transaction.
+func TestBucket_Put_Repeat(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("baz")); err != nil {
+			t.Fatal(err)
+		}
+
+		value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
+		if !bytes.Equal([]byte("baz"), value) {
+			t.Fatalf("unexpected value: %v", value)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can write a bunch of large values.
+func TestBucket_Put_Large(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	count, factor := 100, 200
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := 1; i < count; i++ {
+			if err := b.Put([]byte(strings.Repeat("0", i*factor)), []byte(strings.Repeat("X", (count-i)*factor))); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		for i := 1; i < count; i++ {
+			value := b.Get([]byte(strings.Repeat("0", i*factor)))
+			if !bytes.Equal(value, []byte(strings.Repeat("X", (count-i)*factor))) {
+				t.Fatalf("unexpected value: %v", value)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a database can perform multiple large appends safely.
+func TestDB_Put_VeryLarge(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	n, batchN := 400000, 200000
+	ksize, vsize := 8, 500
+
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	for i := 0; i < n; i += batchN {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, err := tx.CreateBucketIfNotExists([]byte("widgets"))
+			if err != nil {
+				t.Fatal(err)
+			}
+			for j := 0; j < batchN; j++ {
+				k, v := make([]byte, ksize), make([]byte, vsize)
+				binary.BigEndian.PutUint32(k, uint32(i+j))
+				if err := b.Put(k, v); err != nil {
+					t.Fatal(err)
+				}
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+}
+
+// Ensure that a setting a value on a key with a bucket value returns an error.
+func TestBucket_Put_IncompatibleValue(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b0, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if _, err := tx.Bucket([]byte("widgets")).CreateBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b0.Put([]byte("foo"), []byte("bar")); err != bolt.ErrIncompatibleValue {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a setting a value while the transaction is closed returns an error.
+func TestBucket_Put_Closed(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	b, err := tx.CreateBucket([]byte("widgets"))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxClosed {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that setting a value on a read-only bucket returns an error.
+func TestBucket_Put_ReadOnly(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		if err := b.Put([]byte("foo"), []byte("bar")); err != bolt.ErrTxNotWritable {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can delete an existing key.
+func TestBucket_Delete(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Delete([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if v := b.Get([]byte("foo")); v != nil {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a large set of keys will work correctly.
+func TestBucket_Delete_Large(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		for i := 0; i < 100; i++ {
+			if err := b.Put([]byte(strconv.Itoa(i)), []byte(strings.Repeat("*", 1024))); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		for i := 0; i < 100; i++ {
+			if err := b.Delete([]byte(strconv.Itoa(i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		for i := 0; i < 100; i++ {
+			if v := b.Get([]byte(strconv.Itoa(i))); v != nil {
+				t.Fatalf("unexpected value: %v, i=%d", v, i)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Deleting a very large list of keys will cause the freelist to use overflow.
+func TestBucket_Delete_FreelistOverflow(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	k := make([]byte, 16)
+	for i := uint64(0); i < 10000; i++ {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, err := tx.CreateBucketIfNotExists([]byte("0"))
+			if err != nil {
+				t.Fatalf("bucket error: %s", err)
+			}
+
+			for j := uint64(0); j < 1000; j++ {
+				binary.BigEndian.PutUint64(k[:8], i)
+				binary.BigEndian.PutUint64(k[8:], j)
+				if err := b.Put(k, nil); err != nil {
+					t.Fatalf("put error: %s", err)
+				}
+			}
+
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	// Delete all of them in one large transaction
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("0"))
+		c := b.Cursor()
+		for k, _ := c.First(); k != nil; k, _ = c.Next() {
+			if err := c.Delete(); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Check more than an overflow's worth of pages are freed.
+	stats := db.Stats()
+	freePages := stats.FreePageN + stats.PendingPageN
+	if freePages <= 0xFFFF {
+		t.Fatalf("expected more than 0xFFFF free pages, got %v", freePages)
+	}
+
+	// Free page count should be preserved on reopen.
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+	db.MustReopen()
+	if reopenFreePages := db.Stats().FreePageN; freePages != reopenFreePages {
+		t.Fatalf("expected %d free pages, got %+v", freePages, db.Stats())
+	}
+}
+
+// Ensure that deleting of non-existing key is a no-op.
+func TestBucket_Delete_NonExisting(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if _, err = b.CreateBucket([]byte("nested")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		if err := b.Delete([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if b.Bucket([]byte("nested")) == nil {
+			t.Fatal("nested bucket has been deleted")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that accessing and updating nested buckets is ok across transactions.
+func TestBucket_Nested(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create a widgets bucket.
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		// Create a widgets/foo bucket.
+		_, err = b.CreateBucket([]byte("foo"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		// Create a widgets/bar key.
+		if err := b.Put([]byte("bar"), []byte("0000")); err != nil {
+			t.Fatal(err)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.MustCheck()
+
+	// Update widgets/bar.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		if err := b.Put([]byte("bar"), []byte("xxxx")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.MustCheck()
+
+	// Cause a split.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		var b = tx.Bucket([]byte("widgets"))
+		for i := 0; i < 10000; i++ {
+			if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.MustCheck()
+
+	// Insert into widgets/foo/baz.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		var b = tx.Bucket([]byte("widgets"))
+		if err := b.Bucket([]byte("foo")).Put([]byte("baz"), []byte("yyyy")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.MustCheck()
+
+	// Verify.
+	if err := db.View(func(tx *bolt.Tx) error {
+		var b = tx.Bucket([]byte("widgets"))
+		if v := b.Bucket([]byte("foo")).Get([]byte("baz")); !bytes.Equal(v, []byte("yyyy")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		if v := b.Get([]byte("bar")); !bytes.Equal(v, []byte("xxxx")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		for i := 0; i < 10000; i++ {
+			if v := b.Get([]byte(strconv.Itoa(i))); !bytes.Equal(v, []byte(strconv.Itoa(i))) {
+				t.Fatalf("unexpected value: %v", v)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a bucket using Delete() returns an error.
+func TestBucket_Delete_Bucket(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Delete([]byte("foo")); err != bolt.ErrIncompatibleValue {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a key on a read-only bucket returns an error.
+func TestBucket_Delete_ReadOnly(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		if err := tx.Bucket([]byte("widgets")).Delete([]byte("foo")); err != bolt.ErrTxNotWritable {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a deleting value while the transaction is closed returns an error.
+func TestBucket_Delete_Closed(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	b, err := tx.CreateBucket([]byte("widgets"))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+	if err := b.Delete([]byte("foo")); err != bolt.ErrTxClosed {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that deleting a bucket causes nested buckets to be deleted.
+func TestBucket_DeleteBucket_Nested(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		foo, err := widgets.CreateBucket([]byte("foo"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		bar, err := foo.CreateBucket([]byte("bar"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := bar.Put([]byte("baz"), []byte("bat")); err != nil {
+			t.Fatal(err)
+		}
+		if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a bucket causes nested buckets to be deleted after they have been committed.
+func TestBucket_DeleteBucket_Nested2(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		foo, err := widgets.CreateBucket([]byte("foo"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		bar, err := foo.CreateBucket([]byte("bar"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if err := bar.Put([]byte("baz"), []byte("bat")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets := tx.Bucket([]byte("widgets"))
+		if widgets == nil {
+			t.Fatal("expected widgets bucket")
+		}
+
+		foo := widgets.Bucket([]byte("foo"))
+		if foo == nil {
+			t.Fatal("expected foo bucket")
+		}
+
+		bar := foo.Bucket([]byte("bar"))
+		if bar == nil {
+			t.Fatal("expected bar bucket")
+		}
+
+		if v := bar.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		if err := tx.DeleteBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		if tx.Bucket([]byte("widgets")) != nil {
+			t.Fatal("expected bucket to be deleted")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a child bucket with multiple pages causes all pages to get collected.
+// NOTE: Consistency check in bolt_test.DB.Close() will panic if pages not freed properly.
+func TestBucket_DeleteBucket_Large(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		foo, err := widgets.CreateBucket([]byte("foo"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		for i := 0; i < 1000; i++ {
+			if err := foo.Put([]byte(fmt.Sprintf("%d", i)), []byte(fmt.Sprintf("%0100d", i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if err := tx.DeleteBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a simple value retrieved via Bucket() returns a nil.
+func TestBucket_Bucket_IncompatibleValue(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if b := tx.Bucket([]byte("widgets")).Bucket([]byte("foo")); b != nil {
+			t.Fatal("expected nil bucket")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that creating a bucket on an existing non-bucket key returns an error.
+func TestBucket_CreateBucket_IncompatibleValue(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if _, err := widgets.CreateBucket([]byte("foo")); err != bolt.ErrIncompatibleValue {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that deleting a bucket on an existing non-bucket key returns an error.
+func TestBucket_DeleteBucket_IncompatibleValue(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := widgets.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if err := tx.Bucket([]byte("widgets")).DeleteBucket([]byte("foo")); err != bolt.ErrIncompatibleValue {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure bucket can set and update its sequence number.
+func TestBucket_Sequence(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		bkt, err := tx.CreateBucket([]byte("0"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		// Retrieve sequence.
+		if v := bkt.Sequence(); v != 0 {
+			t.Fatalf("unexpected sequence: %d", v)
+		}
+
+		// Update sequence.
+		if err := bkt.SetSequence(1000); err != nil {
+			t.Fatal(err)
+		}
+
+		// Read sequence again.
+		if v := bkt.Sequence(); v != 1000 {
+			t.Fatalf("unexpected sequence: %d", v)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Verify sequence in separate transaction.
+	if err := db.View(func(tx *bolt.Tx) error {
+		if v := tx.Bucket([]byte("0")).Sequence(); v != 1000 {
+			t.Fatalf("unexpected sequence: %d", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can return an autoincrementing sequence.
+func TestBucket_NextSequence(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		widgets, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		woojits, err := tx.CreateBucket([]byte("woojits"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		// Make sure sequence increments.
+		if seq, err := widgets.NextSequence(); err != nil {
+			t.Fatal(err)
+		} else if seq != 1 {
+			t.Fatalf("unexpecte sequence: %d", seq)
+		}
+
+		if seq, err := widgets.NextSequence(); err != nil {
+			t.Fatal(err)
+		} else if seq != 2 {
+			t.Fatalf("unexpected sequence: %d", seq)
+		}
+
+		// Buckets should be separate.
+		if seq, err := woojits.NextSequence(); err != nil {
+			t.Fatal(err)
+		} else if seq != 1 {
+			t.Fatalf("unexpected sequence: %d", 1)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket will persist an autoincrementing sequence even if its
+// the only thing updated on the bucket.
+// https://github.com/boltdb/bolt/issues/296
+func TestBucket_NextSequence_Persist(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.Bucket([]byte("widgets")).NextSequence(); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		seq, err := tx.Bucket([]byte("widgets")).NextSequence()
+		if err != nil {
+			t.Fatalf("unexpected error: %s", err)
+		} else if seq != 2 {
+			t.Fatalf("unexpected sequence: %d", seq)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that retrieving the next sequence on a read-only bucket returns an error.
+func TestBucket_NextSequence_ReadOnly(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		_, err := tx.Bucket([]byte("widgets")).NextSequence()
+		if err != bolt.ErrTxNotWritable {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that retrieving the next sequence for a bucket on a closed database return an error.
+func TestBucket_NextSequence_Closed(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+	b, err := tx.CreateBucket([]byte("widgets"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := b.NextSequence(); err != bolt.ErrTxClosed {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a user can loop over all key/value pairs in a bucket.
+func TestBucket_ForEach(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("0000")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte("0001")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte("0002")); err != nil {
+			t.Fatal(err)
+		}
+
+		var index int
+		if err := b.ForEach(func(k, v []byte) error {
+			switch index {
+			case 0:
+				if !bytes.Equal(k, []byte("bar")) {
+					t.Fatalf("unexpected key: %v", k)
+				} else if !bytes.Equal(v, []byte("0002")) {
+					t.Fatalf("unexpected value: %v", v)
+				}
+			case 1:
+				if !bytes.Equal(k, []byte("baz")) {
+					t.Fatalf("unexpected key: %v", k)
+				} else if !bytes.Equal(v, []byte("0001")) {
+					t.Fatalf("unexpected value: %v", v)
+				}
+			case 2:
+				if !bytes.Equal(k, []byte("foo")) {
+					t.Fatalf("unexpected key: %v", k)
+				} else if !bytes.Equal(v, []byte("0000")) {
+					t.Fatalf("unexpected value: %v", v)
+				}
+			}
+			index++
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		if index != 3 {
+			t.Fatalf("unexpected index: %d", index)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a database can stop iteration early.
+func TestBucket_ForEach_ShortCircuit(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte("0000")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte("0000")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("0000")); err != nil {
+			t.Fatal(err)
+		}
+
+		var index int
+		if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error {
+			index++
+			if bytes.Equal(k, []byte("baz")) {
+				return errors.New("marker")
+			}
+			return nil
+		}); err == nil || err.Error() != "marker" {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		if index != 2 {
+			t.Fatalf("unexpected index: %d", index)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that looping over a bucket on a closed database returns an error.
+func TestBucket_ForEach_Closed(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	b, err := tx.CreateBucket([]byte("widgets"))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := b.ForEach(func(k, v []byte) error { return nil }); err != bolt.ErrTxClosed {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that an error is returned when inserting with an empty key.
+func TestBucket_Put_EmptyKey(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte(""), []byte("bar")); err != bolt.ErrKeyRequired {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		if err := b.Put(nil, []byte("bar")); err != bolt.ErrKeyRequired {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that an error is returned when inserting with a key that's too large.
+func TestBucket_Put_KeyTooLarge(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put(make([]byte, 32769), []byte("bar")); err != bolt.ErrKeyTooLarge {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that an error is returned when inserting a value that's too large.
+func TestBucket_Put_ValueTooLarge(t *testing.T) {
+	// Skip this test on DroneCI because the machine is resource constrained.
+	if os.Getenv("DRONE") == "true" {
+		t.Skip("not enough RAM for test")
+	}
+
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), make([]byte, bolt.MaxValueSize+1)); err != bolt.ErrValueTooLarge {
+			t.Fatalf("unexpected error: %s", err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a bucket can calculate stats.
+func TestBucket_Stats(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Add bucket with fewer keys but one big value.
+	bigKey := []byte("really-big-value")
+	for i := 0; i < 500; i++ {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, err := tx.CreateBucketIfNotExists([]byte("woojits"))
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			if err := b.Put([]byte(fmt.Sprintf("%03d", i)), []byte(strconv.Itoa(i))); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if err := tx.Bucket([]byte("woojits")).Put(bigKey, []byte(strings.Repeat("*", 10000))); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		stats := tx.Bucket([]byte("woojits")).Stats()
+		if stats.BranchPageN != 1 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.LeafPageN != 7 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 2 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.KeyN != 501 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		} else if stats.Depth != 2 {
+			t.Fatalf("unexpected Depth: %d", stats.Depth)
+		}
+
+		branchInuse := 16     // branch page header
+		branchInuse += 7 * 16 // branch elements
+		branchInuse += 7 * 3  // branch keys (6 3-byte keys)
+		if stats.BranchInuse != branchInuse {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		}
+
+		leafInuse := 7 * 16                      // leaf page header
+		leafInuse += 501 * 16                    // leaf elements
+		leafInuse += 500*3 + len(bigKey)         // leaf keys
+		leafInuse += 1*10 + 2*90 + 3*400 + 10000 // leaf values
+		if stats.LeafInuse != leafInuse {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		}
+
+		// Only check allocations for 4KB pages.
+		if db.Info().PageSize == 4096 {
+			if stats.BranchAlloc != 4096 {
+				t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+			} else if stats.LeafAlloc != 36864 {
+				t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+			}
+		}
+
+		if stats.BucketN != 1 {
+			t.Fatalf("unexpected BucketN: %d", stats.BucketN)
+		} else if stats.InlineBucketN != 0 {
+			t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
+		} else if stats.InlineBucketInuse != 0 {
+			t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a bucket with random insertion utilizes fill percentage correctly.
+func TestBucket_Stats_RandomFill(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	} else if os.Getpagesize() != 4096 {
+		t.Skip("invalid page size for test")
+	}
+
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Add a set of values in random order. It will be the same random
+	// order so we can maintain consistency between test runs.
+	var count int
+	rand := rand.New(rand.NewSource(42))
+	for _, i := range rand.Perm(1000) {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, err := tx.CreateBucketIfNotExists([]byte("woojits"))
+			if err != nil {
+				t.Fatal(err)
+			}
+			b.FillPercent = 0.9
+			for _, j := range rand.Perm(100) {
+				index := (j * 10000) + i
+				if err := b.Put([]byte(fmt.Sprintf("%d000000000000000", index)), []byte("0000000000")); err != nil {
+					t.Fatal(err)
+				}
+				count++
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		stats := tx.Bucket([]byte("woojits")).Stats()
+		if stats.KeyN != 100000 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		}
+
+		if stats.BranchPageN != 98 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.BranchInuse != 130984 {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		} else if stats.BranchAlloc != 401408 {
+			t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+		}
+
+		if stats.LeafPageN != 3412 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 0 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.LeafInuse != 4742482 {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		} else if stats.LeafAlloc != 13975552 {
+			t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a bucket can calculate stats.
+func TestBucket_Stats_Small(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Add a bucket that fits on a single root leaf.
+		b, err := tx.CreateBucket([]byte("whozawhats"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("whozawhats"))
+		stats := b.Stats()
+		if stats.BranchPageN != 0 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.LeafPageN != 0 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 0 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.KeyN != 1 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		} else if stats.Depth != 1 {
+			t.Fatalf("unexpected Depth: %d", stats.Depth)
+		} else if stats.BranchInuse != 0 {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		} else if stats.LeafInuse != 0 {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		}
+
+		if db.Info().PageSize == 4096 {
+			if stats.BranchAlloc != 0 {
+				t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+			} else if stats.LeafAlloc != 0 {
+				t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+			}
+		}
+
+		if stats.BucketN != 1 {
+			t.Fatalf("unexpected BucketN: %d", stats.BucketN)
+		} else if stats.InlineBucketN != 1 {
+			t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
+		} else if stats.InlineBucketInuse != 16+16+6 {
+			t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestBucket_Stats_EmptyBucket(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Add a bucket that fits on a single root leaf.
+		if _, err := tx.CreateBucket([]byte("whozawhats")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("whozawhats"))
+		stats := b.Stats()
+		if stats.BranchPageN != 0 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.LeafPageN != 0 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 0 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.KeyN != 0 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		} else if stats.Depth != 1 {
+			t.Fatalf("unexpected Depth: %d", stats.Depth)
+		} else if stats.BranchInuse != 0 {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		} else if stats.LeafInuse != 0 {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		}
+
+		if db.Info().PageSize == 4096 {
+			if stats.BranchAlloc != 0 {
+				t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+			} else if stats.LeafAlloc != 0 {
+				t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+			}
+		}
+
+		if stats.BucketN != 1 {
+			t.Fatalf("unexpected BucketN: %d", stats.BucketN)
+		} else if stats.InlineBucketN != 1 {
+			t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
+		} else if stats.InlineBucketInuse != 16 {
+			t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a bucket can calculate stats.
+func TestBucket_Stats_Nested(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("foo"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := 0; i < 100; i++ {
+			if err := b.Put([]byte(fmt.Sprintf("%02d", i)), []byte(fmt.Sprintf("%02d", i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		bar, err := b.CreateBucket([]byte("bar"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := 0; i < 10; i++ {
+			if err := bar.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		baz, err := bar.CreateBucket([]byte("baz"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := 0; i < 10; i++ {
+			if err := baz.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("foo"))
+		stats := b.Stats()
+		if stats.BranchPageN != 0 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.LeafPageN != 2 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 0 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.KeyN != 122 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		} else if stats.Depth != 3 {
+			t.Fatalf("unexpected Depth: %d", stats.Depth)
+		} else if stats.BranchInuse != 0 {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		}
+
+		foo := 16            // foo (pghdr)
+		foo += 101 * 16      // foo leaf elements
+		foo += 100*2 + 100*2 // foo leaf key/values
+		foo += 3 + 16        // foo -> bar key/value
+
+		bar := 16      // bar (pghdr)
+		bar += 11 * 16 // bar leaf elements
+		bar += 10 + 10 // bar leaf key/values
+		bar += 3 + 16  // bar -> baz key/value
+
+		baz := 16      // baz (inline) (pghdr)
+		baz += 10 * 16 // baz leaf elements
+		baz += 10 + 10 // baz leaf key/values
+
+		if stats.LeafInuse != foo+bar+baz {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		}
+
+		if db.Info().PageSize == 4096 {
+			if stats.BranchAlloc != 0 {
+				t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+			} else if stats.LeafAlloc != 8192 {
+				t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+			}
+		}
+
+		if stats.BucketN != 3 {
+			t.Fatalf("unexpected BucketN: %d", stats.BucketN)
+		} else if stats.InlineBucketN != 1 {
+			t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
+		} else if stats.InlineBucketInuse != baz {
+			t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a large bucket can calculate stats.
+func TestBucket_Stats_Large(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var index int
+	for i := 0; i < 100; i++ {
+		// Add bucket with lots of keys.
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, err := tx.CreateBucketIfNotExists([]byte("widgets"))
+			if err != nil {
+				t.Fatal(err)
+			}
+			for i := 0; i < 1000; i++ {
+				if err := b.Put([]byte(strconv.Itoa(index)), []byte(strconv.Itoa(index))); err != nil {
+					t.Fatal(err)
+				}
+				index++
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	db.MustCheck()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		stats := tx.Bucket([]byte("widgets")).Stats()
+		if stats.BranchPageN != 13 {
+			t.Fatalf("unexpected BranchPageN: %d", stats.BranchPageN)
+		} else if stats.BranchOverflowN != 0 {
+			t.Fatalf("unexpected BranchOverflowN: %d", stats.BranchOverflowN)
+		} else if stats.LeafPageN != 1196 {
+			t.Fatalf("unexpected LeafPageN: %d", stats.LeafPageN)
+		} else if stats.LeafOverflowN != 0 {
+			t.Fatalf("unexpected LeafOverflowN: %d", stats.LeafOverflowN)
+		} else if stats.KeyN != 100000 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		} else if stats.Depth != 3 {
+			t.Fatalf("unexpected Depth: %d", stats.Depth)
+		} else if stats.BranchInuse != 25257 {
+			t.Fatalf("unexpected BranchInuse: %d", stats.BranchInuse)
+		} else if stats.LeafInuse != 2596916 {
+			t.Fatalf("unexpected LeafInuse: %d", stats.LeafInuse)
+		}
+
+		if db.Info().PageSize == 4096 {
+			if stats.BranchAlloc != 53248 {
+				t.Fatalf("unexpected BranchAlloc: %d", stats.BranchAlloc)
+			} else if stats.LeafAlloc != 4898816 {
+				t.Fatalf("unexpected LeafAlloc: %d", stats.LeafAlloc)
+			}
+		}
+
+		if stats.BucketN != 1 {
+			t.Fatalf("unexpected BucketN: %d", stats.BucketN)
+		} else if stats.InlineBucketN != 0 {
+			t.Fatalf("unexpected InlineBucketN: %d", stats.InlineBucketN)
+		} else if stats.InlineBucketInuse != 0 {
+			t.Fatalf("unexpected InlineBucketInuse: %d", stats.InlineBucketInuse)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a bucket can write random keys and values across multiple transactions.
+func TestBucket_Put_Single(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	index := 0
+	if err := quick.Check(func(items testdata) bool {
+		db := MustOpenDB()
+		defer db.MustClose()
+
+		m := make(map[string][]byte)
+
+		if err := db.Update(func(tx *bolt.Tx) error {
+			if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		for _, item := range items {
+			if err := db.Update(func(tx *bolt.Tx) error {
+				if err := tx.Bucket([]byte("widgets")).Put(item.Key, item.Value); err != nil {
+					panic("put error: " + err.Error())
+				}
+				m[string(item.Key)] = item.Value
+				return nil
+			}); err != nil {
+				t.Fatal(err)
+			}
+
+			// Verify all key/values so far.
+			if err := db.View(func(tx *bolt.Tx) error {
+				i := 0
+				for k, v := range m {
+					value := tx.Bucket([]byte("widgets")).Get([]byte(k))
+					if !bytes.Equal(value, v) {
+						t.Logf("value mismatch [run %d] (%d of %d):\nkey: %x\ngot: %x\nexp: %x", index, i, len(m), []byte(k), value, v)
+						db.CopyTempFile()
+						t.FailNow()
+					}
+					i++
+				}
+				return nil
+			}); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		index++
+		return true
+	}, qconfig()); err != nil {
+		t.Error(err)
+	}
+}
+
+// Ensure that a transaction can insert multiple key/value pairs at once.
+func TestBucket_Put_Multiple(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	if err := quick.Check(func(items testdata) bool {
+		db := MustOpenDB()
+		defer db.MustClose()
+
+		// Bulk insert all values.
+		if err := db.Update(func(tx *bolt.Tx) error {
+			if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b := tx.Bucket([]byte("widgets"))
+			for _, item := range items {
+				if err := b.Put(item.Key, item.Value); err != nil {
+					t.Fatal(err)
+				}
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		// Verify all items exist.
+		if err := db.View(func(tx *bolt.Tx) error {
+			b := tx.Bucket([]byte("widgets"))
+			for _, item := range items {
+				value := b.Get(item.Key)
+				if !bytes.Equal(item.Value, value) {
+					db.CopyTempFile()
+					t.Fatalf("exp=%x; got=%x", item.Value, value)
+				}
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		return true
+	}, qconfig()); err != nil {
+		t.Error(err)
+	}
+}
+
+// Ensure that a transaction can delete all key/value pairs and return to a single leaf page.
+func TestBucket_Delete_Quick(t *testing.T) {
+	if testing.Short() {
+		t.Skip("skipping test in short mode.")
+	}
+
+	if err := quick.Check(func(items testdata) bool {
+		db := MustOpenDB()
+		defer db.MustClose()
+
+		// Bulk insert all values.
+		if err := db.Update(func(tx *bolt.Tx) error {
+			if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b := tx.Bucket([]byte("widgets"))
+			for _, item := range items {
+				if err := b.Put(item.Key, item.Value); err != nil {
+					t.Fatal(err)
+				}
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		// Remove items one at a time and check consistency.
+		for _, item := range items {
+			if err := db.Update(func(tx *bolt.Tx) error {
+				return tx.Bucket([]byte("widgets")).Delete(item.Key)
+			}); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		// Anything before our deletion index should be nil.
+		if err := db.View(func(tx *bolt.Tx) error {
+			if err := tx.Bucket([]byte("widgets")).ForEach(func(k, v []byte) error {
+				t.Fatalf("bucket should be empty; found: %06x", trunc(k, 3))
+				return nil
+			}); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+
+		return true
+	}, qconfig()); err != nil {
+		t.Error(err)
+	}
+}
+
+func ExampleBucket_Put() {
+	// Open the database.
+	db, err := bolt.Open(tempfile(), 0666, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer os.Remove(db.Path())
+
+	// Start a write transaction.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create a bucket.
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			return err
+		}
+
+		// Set the value "bar" for the key "foo".
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			return err
+		}
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Read value back in a different read-only transaction.
+	if err := db.View(func(tx *bolt.Tx) error {
+		value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
+		fmt.Printf("The value of 'foo' is: %s\n", value)
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Close database to release file lock.
+	if err := db.Close(); err != nil {
+		log.Fatal(err)
+	}
+
+	// Output:
+	// The value of 'foo' is: bar
+}
+
+func ExampleBucket_Delete() {
+	// Open the database.
+	db, err := bolt.Open(tempfile(), 0666, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer os.Remove(db.Path())
+
+	// Start a write transaction.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create a bucket.
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			return err
+		}
+
+		// Set the value "bar" for the key "foo".
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			return err
+		}
+
+		// Retrieve the key back from the database and verify it.
+		value := b.Get([]byte("foo"))
+		fmt.Printf("The value of 'foo' was: %s\n", value)
+
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Delete the key in a different write transaction.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		return tx.Bucket([]byte("widgets")).Delete([]byte("foo"))
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Retrieve the key again.
+	if err := db.View(func(tx *bolt.Tx) error {
+		value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
+		if value == nil {
+			fmt.Printf("The value of 'foo' is now: nil\n")
+		}
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Close database to release file lock.
+	if err := db.Close(); err != nil {
+		log.Fatal(err)
+	}
+
+	// Output:
+	// The value of 'foo' was: bar
+	// The value of 'foo' is now: nil
+}
+
+func ExampleBucket_ForEach() {
+	// Open the database.
+	db, err := bolt.Open(tempfile(), 0666, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer os.Remove(db.Path())
+
+	// Insert data into a bucket.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("animals"))
+		if err != nil {
+			return err
+		}
+
+		if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
+			return err
+		}
+		if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
+			return err
+		}
+		if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
+			return err
+		}
+
+		// Iterate over items in sorted key order.
+		if err := b.ForEach(func(k, v []byte) error {
+			fmt.Printf("A %s is %s.\n", k, v)
+			return nil
+		}); err != nil {
+			return err
+		}
+
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Close database to release file lock.
+	if err := db.Close(); err != nil {
+		log.Fatal(err)
+	}
+
+	// Output:
+	// A cat is lame.
+	// A dog is fun.
+	// A liger is awesome.
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main.go b/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main.go
new file mode 100644
index 000000000..eb85e05c9
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main.go
@@ -0,0 +1,2136 @@
+package main
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"flag"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"math/rand"
+	"os"
+	"runtime"
+	"runtime/pprof"
+	"strconv"
+	"strings"
+	"time"
+	"unicode"
+	"unicode/utf8"
+	"unsafe"
+
+	bolt "github.com/coreos/bbolt"
+)
+
+var (
+	// ErrUsage is returned when a usage message was printed and the process
+	// should simply exit with an error.
+	ErrUsage = errors.New("usage")
+
+	// ErrUnknownCommand is returned when a CLI command is not specified.
+	ErrUnknownCommand = errors.New("unknown command")
+
+	// ErrPathRequired is returned when the path to a Bolt database is not specified.
+	ErrPathRequired = errors.New("path required")
+
+	// ErrFileNotFound is returned when a Bolt database does not exist.
+	ErrFileNotFound = errors.New("file not found")
+
+	// ErrInvalidValue is returned when a benchmark reads an unexpected value.
+	ErrInvalidValue = errors.New("invalid value")
+
+	// ErrCorrupt is returned when a checking a data file finds errors.
+	ErrCorrupt = errors.New("invalid value")
+
+	// ErrNonDivisibleBatchSize is returned when the batch size can't be evenly
+	// divided by the iteration count.
+	ErrNonDivisibleBatchSize = errors.New("number of iterations must be divisible by the batch size")
+
+	// ErrPageIDRequired is returned when a required page id is not specified.
+	ErrPageIDRequired = errors.New("page id required")
+
+	// ErrBucketRequired is returned when a bucket is not specified.
+	ErrBucketRequired = errors.New("bucket required")
+
+	// ErrBucketNotFound is returned when a bucket is not found.
+	ErrBucketNotFound = errors.New("bucket not found")
+
+	// ErrKeyRequired is returned when a key is not specified.
+	ErrKeyRequired = errors.New("key required")
+
+	// ErrKeyNotFound is returned when a key is not found.
+	ErrKeyNotFound = errors.New("key not found")
+)
+
+// PageHeaderSize represents the size of the bolt.page header.
+const PageHeaderSize = 16
+
+func main() {
+	m := NewMain()
+	if err := m.Run(os.Args[1:]...); err == ErrUsage {
+		os.Exit(2)
+	} else if err != nil {
+		fmt.Println(err.Error())
+		os.Exit(1)
+	}
+}
+
+// Main represents the main program execution.
+type Main struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewMain returns a new instance of Main connect to the standard input/output.
+func NewMain() *Main {
+	return &Main{
+		Stdin:  os.Stdin,
+		Stdout: os.Stdout,
+		Stderr: os.Stderr,
+	}
+}
+
+// Run executes the program.
+func (m *Main) Run(args ...string) error {
+	// Require a command at the beginning.
+	if len(args) == 0 || strings.HasPrefix(args[0], "-") {
+		fmt.Fprintln(m.Stderr, m.Usage())
+		return ErrUsage
+	}
+
+	// Execute command.
+	switch args[0] {
+	case "help":
+		fmt.Fprintln(m.Stderr, m.Usage())
+		return ErrUsage
+	case "bench":
+		return newBenchCommand(m).Run(args[1:]...)
+	case "buckets":
+		return newBucketsCommand(m).Run(args[1:]...)
+	case "check":
+		return newCheckCommand(m).Run(args[1:]...)
+	case "compact":
+		return newCompactCommand(m).Run(args[1:]...)
+	case "dump":
+		return newDumpCommand(m).Run(args[1:]...)
+	case "page-item":
+		return newPageItemCommand(m).Run(args[1:]...)
+	case "get":
+		return newGetCommand(m).Run(args[1:]...)
+	case "info":
+		return newInfoCommand(m).Run(args[1:]...)
+	case "keys":
+		return newKeysCommand(m).Run(args[1:]...)
+	case "page":
+		return newPageCommand(m).Run(args[1:]...)
+	case "pages":
+		return newPagesCommand(m).Run(args[1:]...)
+	case "stats":
+		return newStatsCommand(m).Run(args[1:]...)
+	default:
+		return ErrUnknownCommand
+	}
+}
+
+// Usage returns the help message.
+func (m *Main) Usage() string {
+	return strings.TrimLeft(`
+Bolt is a tool for inspecting bolt databases.
+
+Usage:
+
+	bolt command [arguments]
+
+The commands are:
+
+    bench       run synthetic benchmark against bolt
+    buckets     print a list of buckets
+    check       verifies integrity of bolt database
+    compact     copies a bolt database, compacting it in the process
+    dump        print a hexadecimal dump of a single page
+    get         print the value of a key in a bucket
+    info        print basic info
+    keys        print a list of keys in a bucket
+    help        print this screen
+    page        print one or more pages in human readable format
+    pages       print list of pages with their types
+    page-item   print the key and value of a page item.
+    stats       iterate over all pages and generate usage stats
+
+Use "bolt [command] -h" for more information about a command.
+`, "\n")
+}
+
+// CheckCommand represents the "check" command execution.
+type CheckCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewCheckCommand returns a CheckCommand.
+func newCheckCommand(m *Main) *CheckCommand {
+	return &CheckCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *CheckCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	// Perform consistency check.
+	return db.View(func(tx *bolt.Tx) error {
+		var count int
+		for err := range tx.Check() {
+			fmt.Fprintln(cmd.Stdout, err)
+			count++
+		}
+
+		// Print summary of errors.
+		if count > 0 {
+			fmt.Fprintf(cmd.Stdout, "%d errors found\n", count)
+			return ErrCorrupt
+		}
+
+		// Notify user that database is valid.
+		fmt.Fprintln(cmd.Stdout, "OK")
+		return nil
+	})
+}
+
+// Usage returns the help message.
+func (cmd *CheckCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt check PATH
+
+Check opens a database at PATH and runs an exhaustive check to verify that
+all pages are accessible or are marked as freed. It also verifies that no
+pages are double referenced.
+
+Verification errors will stream out as they are found and the process will
+return after all pages have been checked.
+`, "\n")
+}
+
+// InfoCommand represents the "info" command execution.
+type InfoCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewInfoCommand returns a InfoCommand.
+func newInfoCommand(m *Main) *InfoCommand {
+	return &InfoCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *InfoCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Open the database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	// Print basic database info.
+	info := db.Info()
+	fmt.Fprintf(cmd.Stdout, "Page Size: %d\n", info.PageSize)
+
+	return nil
+}
+
+// Usage returns the help message.
+func (cmd *InfoCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt info PATH
+
+Info prints basic information about the Bolt database at PATH.
+`, "\n")
+}
+
+// DumpCommand represents the "dump" command execution.
+type DumpCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// newDumpCommand returns a DumpCommand.
+func newDumpCommand(m *Main) *DumpCommand {
+	return &DumpCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *DumpCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path and page id.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Read page ids.
+	pageIDs, err := atois(fs.Args()[1:])
+	if err != nil {
+		return err
+	} else if len(pageIDs) == 0 {
+		return ErrPageIDRequired
+	}
+
+	// Open database to retrieve page size.
+	pageSize, err := ReadPageSize(path)
+	if err != nil {
+		return err
+	}
+
+	// Open database file handler.
+	f, err := os.Open(path)
+	if err != nil {
+		return err
+	}
+	defer func() { _ = f.Close() }()
+
+	// Print each page listed.
+	for i, pageID := range pageIDs {
+		// Print a separator.
+		if i > 0 {
+			fmt.Fprintln(cmd.Stdout, "===============================================")
+		}
+
+		// Print page to stdout.
+		if err := cmd.PrintPage(cmd.Stdout, f, pageID, pageSize); err != nil {
+			return err
+		}
+	}
+
+	return nil
+}
+
+// PrintPage prints a given page as hexadecimal.
+func (cmd *DumpCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
+	const bytesPerLineN = 16
+
+	// Read page into buffer.
+	buf := make([]byte, pageSize)
+	addr := pageID * pageSize
+	if n, err := r.ReadAt(buf, int64(addr)); err != nil {
+		return err
+	} else if n != pageSize {
+		return io.ErrUnexpectedEOF
+	}
+
+	// Write out to writer in 16-byte lines.
+	var prev []byte
+	var skipped bool
+	for offset := 0; offset < pageSize; offset += bytesPerLineN {
+		// Retrieve current 16-byte line.
+		line := buf[offset : offset+bytesPerLineN]
+		isLastLine := (offset == (pageSize - bytesPerLineN))
+
+		// If it's the same as the previous line then print a skip.
+		if bytes.Equal(line, prev) && !isLastLine {
+			if !skipped {
+				fmt.Fprintf(w, "%07x *\n", addr+offset)
+				skipped = true
+			}
+		} else {
+			// Print line as hexadecimal in 2-byte groups.
+			fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
+				line[0:2], line[2:4], line[4:6], line[6:8],
+				line[8:10], line[10:12], line[12:14], line[14:16],
+			)
+
+			skipped = false
+		}
+
+		// Save the previous line.
+		prev = line
+	}
+	fmt.Fprint(w, "\n")
+
+	return nil
+}
+
+// Usage returns the help message.
+func (cmd *DumpCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt dump PATH pageid [pageid...]
+
+Dump prints a hexadecimal dump of one or more pages.
+`, "\n")
+}
+
+// PageItemCommand represents the "page-item" command execution.
+type PageItemCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// newPageItemCommand returns a PageItemCommand.
+func newPageItemCommand(m *Main) *PageItemCommand {
+	return &PageItemCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+type pageItemOptions struct {
+	help      bool
+	keyOnly   bool
+	valueOnly bool
+	format    string
+}
+
+// Run executes the command.
+func (cmd *PageItemCommand) Run(args ...string) error {
+	// Parse flags.
+	options := &pageItemOptions{}
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	fs.BoolVar(&options.keyOnly, "key-only", false, "Print only the key")
+	fs.BoolVar(&options.valueOnly, "value-only", false, "Print only the value")
+	fs.StringVar(&options.format, "format", "ascii-encoded", "Output format. One of: ascii-encoded|hex|bytes")
+	fs.BoolVar(&options.help, "h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if options.help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	if options.keyOnly && options.valueOnly {
+		return fmt.Errorf("The --key-only or --value-only flag may be set, but not both.")
+	}
+
+	// Require database path and page id.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Read page id.
+	pageID, err := strconv.Atoi(fs.Arg(1))
+	if err != nil {
+		return err
+	}
+
+	// Read item id.
+	itemID, err := strconv.Atoi(fs.Arg(2))
+	if err != nil {
+		return err
+	}
+
+	// Open database file handler.
+	f, err := os.Open(path)
+	if err != nil {
+		return err
+	}
+	defer func() { _ = f.Close() }()
+
+	// Retrieve page info and page size.
+	_, buf, err := ReadPage(path, pageID)
+	if err != nil {
+		return err
+	}
+
+	if !options.valueOnly {
+		err := cmd.PrintLeafItemKey(cmd.Stdout, buf, uint16(itemID), options.format)
+		if err != nil {
+			return err
+		}
+	}
+	if !options.keyOnly {
+		err := cmd.PrintLeafItemValue(cmd.Stdout, buf, uint16(itemID), options.format)
+		if err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// leafPageElement retrieves a leaf page element.
+func (cmd *PageItemCommand) leafPageElement(pageBytes []byte, index uint16) (*leafPageElement, error) {
+	p := (*page)(unsafe.Pointer(&pageBytes[0]))
+	if index >= p.count {
+		return nil, fmt.Errorf("leafPageElement: expected item index less than %d, but got %d.", p.count, index)
+	}
+	if p.Type() != "leaf" {
+		return nil, fmt.Errorf("leafPageElement: expected page type of 'leaf', but got '%s'", p.Type())
+	}
+	return p.leafPageElement(index), nil
+}
+
+// writeBytes writes the byte to the writer. Supported formats: ascii-encoded, hex, bytes.
+func (cmd *PageItemCommand) writeBytes(w io.Writer, b []byte, format string) error {
+	switch format {
+	case "ascii-encoded":
+		_, err := fmt.Fprintf(w, "%q", b)
+		if err != nil {
+			return err
+		}
+		_, err = fmt.Fprintf(w, "\n")
+		return err
+	case "hex":
+		_, err := fmt.Fprintf(w, "%x", b)
+		if err != nil {
+			return err
+		}
+		_, err = fmt.Fprintf(w, "\n")
+		return err
+	case "bytes":
+		_, err := w.Write(b)
+		return err
+	default:
+		return fmt.Errorf("writeBytes: unsupported format: %s", format)
+	}
+}
+
+// PrintLeafItemKey writes the bytes of a leaf element's key.
+func (cmd *PageItemCommand) PrintLeafItemKey(w io.Writer, pageBytes []byte, index uint16, format string) error {
+	e, err := cmd.leafPageElement(pageBytes, index)
+	if err != nil {
+		return err
+	}
+	return cmd.writeBytes(w, e.key(), format)
+}
+
+// PrintLeafItemKey writes the bytes of a leaf element's value.
+func (cmd *PageItemCommand) PrintLeafItemValue(w io.Writer, pageBytes []byte, index uint16, format string) error {
+	e, err := cmd.leafPageElement(pageBytes, index)
+	if err != nil {
+		return err
+	}
+	return cmd.writeBytes(w, e.value(), format)
+}
+
+// Usage returns the help message.
+func (cmd *PageItemCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt page-item [options] PATH pageid itemid
+
+Additional options include:
+
+	--key-only
+		Print only the key
+	--value-only
+		Print only the value
+	--format
+		Output format. One of: ascii-encoded|hex|bytes (default=ascii-encoded)
+
+page-item prints a page item key and value.
+`, "\n")
+}
+
+// PageCommand represents the "page" command execution.
+type PageCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// newPageCommand returns a PageCommand.
+func newPageCommand(m *Main) *PageCommand {
+	return &PageCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *PageCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path and page id.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Read page ids.
+	pageIDs, err := atois(fs.Args()[1:])
+	if err != nil {
+		return err
+	} else if len(pageIDs) == 0 {
+		return ErrPageIDRequired
+	}
+
+	// Open database file handler.
+	f, err := os.Open(path)
+	if err != nil {
+		return err
+	}
+	defer func() { _ = f.Close() }()
+
+	// Print each page listed.
+	for i, pageID := range pageIDs {
+		// Print a separator.
+		if i > 0 {
+			fmt.Fprintln(cmd.Stdout, "===============================================")
+		}
+
+		// Retrieve page info and page size.
+		p, buf, err := ReadPage(path, pageID)
+		if err != nil {
+			return err
+		}
+
+		// Print basic page info.
+		fmt.Fprintf(cmd.Stdout, "Page ID:    %d\n", p.id)
+		fmt.Fprintf(cmd.Stdout, "Page Type:  %s\n", p.Type())
+		fmt.Fprintf(cmd.Stdout, "Total Size: %d bytes\n", len(buf))
+
+		// Print type-specific data.
+		switch p.Type() {
+		case "meta":
+			err = cmd.PrintMeta(cmd.Stdout, buf)
+		case "leaf":
+			err = cmd.PrintLeaf(cmd.Stdout, buf)
+		case "branch":
+			err = cmd.PrintBranch(cmd.Stdout, buf)
+		case "freelist":
+			err = cmd.PrintFreelist(cmd.Stdout, buf)
+		}
+		if err != nil {
+			return err
+		}
+	}
+
+	return nil
+}
+
+// PrintMeta prints the data from the meta page.
+func (cmd *PageCommand) PrintMeta(w io.Writer, buf []byte) error {
+	m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
+	fmt.Fprintf(w, "Version:    %d\n", m.version)
+	fmt.Fprintf(w, "Page Size:  %d bytes\n", m.pageSize)
+	fmt.Fprintf(w, "Flags:      %08x\n", m.flags)
+	fmt.Fprintf(w, "Root:       <pgid=%d>\n", m.root.root)
+	fmt.Fprintf(w, "Freelist:   <pgid=%d>\n", m.freelist)
+	fmt.Fprintf(w, "HWM:        <pgid=%d>\n", m.pgid)
+	fmt.Fprintf(w, "Txn ID:     %d\n", m.txid)
+	fmt.Fprintf(w, "Checksum:   %016x\n", m.checksum)
+	fmt.Fprintf(w, "\n")
+	return nil
+}
+
+// PrintLeaf prints the data for a leaf page.
+func (cmd *PageCommand) PrintLeaf(w io.Writer, buf []byte) error {
+	p := (*page)(unsafe.Pointer(&buf[0]))
+
+	// Print number of items.
+	fmt.Fprintf(w, "Item Count: %d\n", p.count)
+	fmt.Fprintf(w, "\n")
+
+	// Print each key/value.
+	for i := uint16(0); i < p.count; i++ {
+		e := p.leafPageElement(i)
+
+		// Format key as string.
+		var k string
+		if isPrintable(string(e.key())) {
+			k = fmt.Sprintf("%q", string(e.key()))
+		} else {
+			k = fmt.Sprintf("%x", string(e.key()))
+		}
+
+		// Format value as string.
+		var v string
+		if (e.flags & uint32(bucketLeafFlag)) != 0 {
+			b := (*bucket)(unsafe.Pointer(&e.value()[0]))
+			v = fmt.Sprintf("<pgid=%d,seq=%d>", b.root, b.sequence)
+		} else if isPrintable(string(e.value())) {
+			v = fmt.Sprintf("%q", string(e.value()))
+		} else {
+			v = fmt.Sprintf("%x", string(e.value()))
+		}
+
+		fmt.Fprintf(w, "%s: %s\n", k, v)
+	}
+	fmt.Fprintf(w, "\n")
+	return nil
+}
+
+// PrintBranch prints the data for a leaf page.
+func (cmd *PageCommand) PrintBranch(w io.Writer, buf []byte) error {
+	p := (*page)(unsafe.Pointer(&buf[0]))
+
+	// Print number of items.
+	fmt.Fprintf(w, "Item Count: %d\n", p.count)
+	fmt.Fprintf(w, "\n")
+
+	// Print each key/value.
+	for i := uint16(0); i < p.count; i++ {
+		e := p.branchPageElement(i)
+
+		// Format key as string.
+		var k string
+		if isPrintable(string(e.key())) {
+			k = fmt.Sprintf("%q", string(e.key()))
+		} else {
+			k = fmt.Sprintf("%x", string(e.key()))
+		}
+
+		fmt.Fprintf(w, "%s: <pgid=%d>\n", k, e.pgid)
+	}
+	fmt.Fprintf(w, "\n")
+	return nil
+}
+
+// PrintFreelist prints the data for a freelist page.
+func (cmd *PageCommand) PrintFreelist(w io.Writer, buf []byte) error {
+	p := (*page)(unsafe.Pointer(&buf[0]))
+
+	// Check for overflow and, if present, adjust starting index and actual element count.
+	idx, count := 0, int(p.count)
+	if p.count == 0xFFFF {
+		idx = 1
+		count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0])
+	}
+
+	// Print number of items.
+	fmt.Fprintf(w, "Item Count: %d\n", count)
+	fmt.Fprintf(w, "Overflow: %d\n", p.overflow)
+
+	fmt.Fprintf(w, "\n")
+
+	// Print each page in the freelist.
+	ids := (*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr))
+	for i := int(idx); i < count; i++ {
+		fmt.Fprintf(w, "%d\n", ids[i])
+	}
+	fmt.Fprintf(w, "\n")
+	return nil
+}
+
+// PrintPage prints a given page as hexadecimal.
+func (cmd *PageCommand) PrintPage(w io.Writer, r io.ReaderAt, pageID int, pageSize int) error {
+	const bytesPerLineN = 16
+
+	// Read page into buffer.
+	buf := make([]byte, pageSize)
+	addr := pageID * pageSize
+	if n, err := r.ReadAt(buf, int64(addr)); err != nil {
+		return err
+	} else if n != pageSize {
+		return io.ErrUnexpectedEOF
+	}
+
+	// Write out to writer in 16-byte lines.
+	var prev []byte
+	var skipped bool
+	for offset := 0; offset < pageSize; offset += bytesPerLineN {
+		// Retrieve current 16-byte line.
+		line := buf[offset : offset+bytesPerLineN]
+		isLastLine := (offset == (pageSize - bytesPerLineN))
+
+		// If it's the same as the previous line then print a skip.
+		if bytes.Equal(line, prev) && !isLastLine {
+			if !skipped {
+				fmt.Fprintf(w, "%07x *\n", addr+offset)
+				skipped = true
+			}
+		} else {
+			// Print line as hexadecimal in 2-byte groups.
+			fmt.Fprintf(w, "%07x %04x %04x %04x %04x %04x %04x %04x %04x\n", addr+offset,
+				line[0:2], line[2:4], line[4:6], line[6:8],
+				line[8:10], line[10:12], line[12:14], line[14:16],
+			)
+
+			skipped = false
+		}
+
+		// Save the previous line.
+		prev = line
+	}
+	fmt.Fprint(w, "\n")
+
+	return nil
+}
+
+// Usage returns the help message.
+func (cmd *PageCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt page PATH pageid [pageid...]
+
+Page prints one or more pages in human readable format.
+`, "\n")
+}
+
+// PagesCommand represents the "pages" command execution.
+type PagesCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewPagesCommand returns a PagesCommand.
+func newPagesCommand(m *Main) *PagesCommand {
+	return &PagesCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *PagesCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer func() { _ = db.Close() }()
+
+	// Write header.
+	fmt.Fprintln(cmd.Stdout, "ID       TYPE       ITEMS  OVRFLW")
+	fmt.Fprintln(cmd.Stdout, "======== ========== ====== ======")
+
+	return db.Update(func(tx *bolt.Tx) error {
+		var id int
+		for {
+			p, err := tx.Page(id)
+			if err != nil {
+				return &PageError{ID: id, Err: err}
+			} else if p == nil {
+				break
+			}
+
+			// Only display count and overflow if this is a non-free page.
+			var count, overflow string
+			if p.Type != "free" {
+				count = strconv.Itoa(p.Count)
+				if p.OverflowCount > 0 {
+					overflow = strconv.Itoa(p.OverflowCount)
+				}
+			}
+
+			// Print table row.
+			fmt.Fprintf(cmd.Stdout, "%-8d %-10s %-6s %-6s\n", p.ID, p.Type, count, overflow)
+
+			// Move to the next non-overflow page.
+			id += 1
+			if p.Type != "free" {
+				id += p.OverflowCount
+			}
+		}
+		return nil
+	})
+}
+
+// Usage returns the help message.
+func (cmd *PagesCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt pages PATH
+
+Pages prints a table of pages with their type (meta, leaf, branch, freelist).
+Leaf and branch pages will show a key count in the "items" column while the
+freelist will show the number of free pages in the "items" column.
+
+The "overflow" column shows the number of blocks that the page spills over
+into. Normally there is no overflow but large keys and values can cause
+a single page to take up multiple blocks.
+`, "\n")
+}
+
+// StatsCommand represents the "stats" command execution.
+type StatsCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewStatsCommand returns a StatsCommand.
+func newStatsCommand(m *Main) *StatsCommand {
+	return &StatsCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *StatsCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path.
+	path, prefix := fs.Arg(0), fs.Arg(1)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	return db.View(func(tx *bolt.Tx) error {
+		var s bolt.BucketStats
+		var count int
+		if err := tx.ForEach(func(name []byte, b *bolt.Bucket) error {
+			if bytes.HasPrefix(name, []byte(prefix)) {
+				s.Add(b.Stats())
+				count += 1
+			}
+			return nil
+		}); err != nil {
+			return err
+		}
+
+		fmt.Fprintf(cmd.Stdout, "Aggregate statistics for %d buckets\n\n", count)
+
+		fmt.Fprintln(cmd.Stdout, "Page count statistics")
+		fmt.Fprintf(cmd.Stdout, "\tNumber of logical branch pages: %d\n", s.BranchPageN)
+		fmt.Fprintf(cmd.Stdout, "\tNumber of physical branch overflow pages: %d\n", s.BranchOverflowN)
+		fmt.Fprintf(cmd.Stdout, "\tNumber of logical leaf pages: %d\n", s.LeafPageN)
+		fmt.Fprintf(cmd.Stdout, "\tNumber of physical leaf overflow pages: %d\n", s.LeafOverflowN)
+
+		fmt.Fprintln(cmd.Stdout, "Tree statistics")
+		fmt.Fprintf(cmd.Stdout, "\tNumber of keys/value pairs: %d\n", s.KeyN)
+		fmt.Fprintf(cmd.Stdout, "\tNumber of levels in B+tree: %d\n", s.Depth)
+
+		fmt.Fprintln(cmd.Stdout, "Page size utilization")
+		fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical branch pages: %d\n", s.BranchAlloc)
+		var percentage int
+		if s.BranchAlloc != 0 {
+			percentage = int(float32(s.BranchInuse) * 100.0 / float32(s.BranchAlloc))
+		}
+		fmt.Fprintf(cmd.Stdout, "\tBytes actually used for branch data: %d (%d%%)\n", s.BranchInuse, percentage)
+		fmt.Fprintf(cmd.Stdout, "\tBytes allocated for physical leaf pages: %d\n", s.LeafAlloc)
+		percentage = 0
+		if s.LeafAlloc != 0 {
+			percentage = int(float32(s.LeafInuse) * 100.0 / float32(s.LeafAlloc))
+		}
+		fmt.Fprintf(cmd.Stdout, "\tBytes actually used for leaf data: %d (%d%%)\n", s.LeafInuse, percentage)
+
+		fmt.Fprintln(cmd.Stdout, "Bucket statistics")
+		fmt.Fprintf(cmd.Stdout, "\tTotal number of buckets: %d\n", s.BucketN)
+		percentage = 0
+		if s.BucketN != 0 {
+			percentage = int(float32(s.InlineBucketN) * 100.0 / float32(s.BucketN))
+		}
+		fmt.Fprintf(cmd.Stdout, "\tTotal number on inlined buckets: %d (%d%%)\n", s.InlineBucketN, percentage)
+		percentage = 0
+		if s.LeafInuse != 0 {
+			percentage = int(float32(s.InlineBucketInuse) * 100.0 / float32(s.LeafInuse))
+		}
+		fmt.Fprintf(cmd.Stdout, "\tBytes used for inlined buckets: %d (%d%%)\n", s.InlineBucketInuse, percentage)
+
+		return nil
+	})
+}
+
+// Usage returns the help message.
+func (cmd *StatsCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt stats PATH
+
+Stats performs an extensive search of the database to track every page
+reference. It starts at the current meta page and recursively iterates
+through every accessible bucket.
+
+The following errors can be reported:
+
+    already freed
+        The page is referenced more than once in the freelist.
+
+    unreachable unfreed
+        The page is not referenced by a bucket or in the freelist.
+
+    reachable freed
+        The page is referenced by a bucket but is also in the freelist.
+
+    out of bounds
+        A page is referenced that is above the high water mark.
+
+    multiple references
+        A page is referenced by more than one other page.
+
+    invalid type
+        The page type is not "meta", "leaf", "branch", or "freelist".
+
+No errors should occur in your database. However, if for some reason you
+experience corruption, please submit a ticket to the Bolt project page:
+
+  https://github.com/boltdb/bolt/issues
+`, "\n")
+}
+
+// BucketsCommand represents the "buckets" command execution.
+type BucketsCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewBucketsCommand returns a BucketsCommand.
+func newBucketsCommand(m *Main) *BucketsCommand {
+	return &BucketsCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *BucketsCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path.
+	path := fs.Arg(0)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	// Print buckets.
+	return db.View(func(tx *bolt.Tx) error {
+		return tx.ForEach(func(name []byte, _ *bolt.Bucket) error {
+			fmt.Fprintln(cmd.Stdout, string(name))
+			return nil
+		})
+	})
+}
+
+// Usage returns the help message.
+func (cmd *BucketsCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt buckets PATH
+
+Print a list of buckets.
+`, "\n")
+}
+
+// KeysCommand represents the "keys" command execution.
+type KeysCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewKeysCommand returns a KeysCommand.
+func newKeysCommand(m *Main) *KeysCommand {
+	return &KeysCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *KeysCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path and bucket.
+	path, bucket := fs.Arg(0), fs.Arg(1)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	} else if bucket == "" {
+		return ErrBucketRequired
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	// Print keys.
+	return db.View(func(tx *bolt.Tx) error {
+		// Find bucket.
+		b := tx.Bucket([]byte(bucket))
+		if b == nil {
+			return ErrBucketNotFound
+		}
+
+		// Iterate over each key.
+		return b.ForEach(func(key, _ []byte) error {
+			fmt.Fprintln(cmd.Stdout, string(key))
+			return nil
+		})
+	})
+}
+
+// Usage returns the help message.
+func (cmd *KeysCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt keys PATH BUCKET
+
+Print a list of keys in the given bucket.
+`, "\n")
+}
+
+// GetCommand represents the "get" command execution.
+type GetCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewGetCommand returns a GetCommand.
+func newGetCommand(m *Main) *GetCommand {
+	return &GetCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *GetCommand) Run(args ...string) error {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	help := fs.Bool("h", false, "")
+	if err := fs.Parse(args); err != nil {
+		return err
+	} else if *help {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	}
+
+	// Require database path, bucket and key.
+	path, bucket, key := fs.Arg(0), fs.Arg(1), fs.Arg(2)
+	if path == "" {
+		return ErrPathRequired
+	} else if _, err := os.Stat(path); os.IsNotExist(err) {
+		return ErrFileNotFound
+	} else if bucket == "" {
+		return ErrBucketRequired
+	} else if key == "" {
+		return ErrKeyRequired
+	}
+
+	// Open database.
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+
+	// Print value.
+	return db.View(func(tx *bolt.Tx) error {
+		// Find bucket.
+		b := tx.Bucket([]byte(bucket))
+		if b == nil {
+			return ErrBucketNotFound
+		}
+
+		// Find value for given key.
+		val := b.Get([]byte(key))
+		if val == nil {
+			return ErrKeyNotFound
+		}
+
+		fmt.Fprintln(cmd.Stdout, string(val))
+		return nil
+	})
+}
+
+// Usage returns the help message.
+func (cmd *GetCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt get PATH BUCKET KEY
+
+Print the value of the given key in the given bucket.
+`, "\n")
+}
+
+var benchBucketName = []byte("bench")
+
+// BenchCommand represents the "bench" command execution.
+type BenchCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+}
+
+// NewBenchCommand returns a BenchCommand using the
+func newBenchCommand(m *Main) *BenchCommand {
+	return &BenchCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the "bench" command.
+func (cmd *BenchCommand) Run(args ...string) error {
+	// Parse CLI arguments.
+	options, err := cmd.ParseFlags(args)
+	if err != nil {
+		return err
+	}
+
+	// Remove path if "-work" is not set. Otherwise keep path.
+	if options.Work {
+		fmt.Fprintf(cmd.Stdout, "work: %s\n", options.Path)
+	} else {
+		defer os.Remove(options.Path)
+	}
+
+	// Create database.
+	db, err := bolt.Open(options.Path, 0666, nil)
+	if err != nil {
+		return err
+	}
+	db.NoSync = options.NoSync
+	defer db.Close()
+
+	// Write to the database.
+	var results BenchResults
+	if err := cmd.runWrites(db, options, &results); err != nil {
+		return fmt.Errorf("write: %v", err)
+	}
+
+	// Read from the database.
+	if err := cmd.runReads(db, options, &results); err != nil {
+		return fmt.Errorf("bench: read: %s", err)
+	}
+
+	// Print results.
+	fmt.Fprintf(os.Stderr, "# Write\t%v\t(%v/op)\t(%v op/sec)\n", results.WriteDuration, results.WriteOpDuration(), results.WriteOpsPerSecond())
+	fmt.Fprintf(os.Stderr, "# Read\t%v\t(%v/op)\t(%v op/sec)\n", results.ReadDuration, results.ReadOpDuration(), results.ReadOpsPerSecond())
+	fmt.Fprintln(os.Stderr, "")
+	return nil
+}
+
+// ParseFlags parses the command line flags.
+func (cmd *BenchCommand) ParseFlags(args []string) (*BenchOptions, error) {
+	var options BenchOptions
+
+	// Parse flagset.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	fs.StringVar(&options.ProfileMode, "profile-mode", "rw", "")
+	fs.StringVar(&options.WriteMode, "write-mode", "seq", "")
+	fs.StringVar(&options.ReadMode, "read-mode", "seq", "")
+	fs.IntVar(&options.Iterations, "count", 1000, "")
+	fs.IntVar(&options.BatchSize, "batch-size", 0, "")
+	fs.IntVar(&options.KeySize, "key-size", 8, "")
+	fs.IntVar(&options.ValueSize, "value-size", 32, "")
+	fs.StringVar(&options.CPUProfile, "cpuprofile", "", "")
+	fs.StringVar(&options.MemProfile, "memprofile", "", "")
+	fs.StringVar(&options.BlockProfile, "blockprofile", "", "")
+	fs.Float64Var(&options.FillPercent, "fill-percent", bolt.DefaultFillPercent, "")
+	fs.BoolVar(&options.NoSync, "no-sync", false, "")
+	fs.BoolVar(&options.Work, "work", false, "")
+	fs.StringVar(&options.Path, "path", "", "")
+	fs.SetOutput(cmd.Stderr)
+	if err := fs.Parse(args); err != nil {
+		return nil, err
+	}
+
+	// Set batch size to iteration size if not set.
+	// Require that batch size can be evenly divided by the iteration count.
+	if options.BatchSize == 0 {
+		options.BatchSize = options.Iterations
+	} else if options.Iterations%options.BatchSize != 0 {
+		return nil, ErrNonDivisibleBatchSize
+	}
+
+	// Generate temp path if one is not passed in.
+	if options.Path == "" {
+		f, err := ioutil.TempFile("", "bolt-bench-")
+		if err != nil {
+			return nil, fmt.Errorf("temp file: %s", err)
+		}
+		f.Close()
+		os.Remove(f.Name())
+		options.Path = f.Name()
+	}
+
+	return &options, nil
+}
+
+// Writes to the database.
+func (cmd *BenchCommand) runWrites(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	// Start profiling for writes.
+	if options.ProfileMode == "rw" || options.ProfileMode == "w" {
+		cmd.startProfiling(options)
+	}
+
+	t := time.Now()
+
+	var err error
+	switch options.WriteMode {
+	case "seq":
+		err = cmd.runWritesSequential(db, options, results)
+	case "rnd":
+		err = cmd.runWritesRandom(db, options, results)
+	case "seq-nest":
+		err = cmd.runWritesSequentialNested(db, options, results)
+	case "rnd-nest":
+		err = cmd.runWritesRandomNested(db, options, results)
+	default:
+		return fmt.Errorf("invalid write mode: %s", options.WriteMode)
+	}
+
+	// Save time to write.
+	results.WriteDuration = time.Since(t)
+
+	// Stop profiling for writes only.
+	if options.ProfileMode == "w" {
+		cmd.stopProfiling()
+	}
+
+	return err
+}
+
+func (cmd *BenchCommand) runWritesSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	var i = uint32(0)
+	return cmd.runWritesWithSource(db, options, results, func() uint32 { i++; return i })
+}
+
+func (cmd *BenchCommand) runWritesRandom(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	r := rand.New(rand.NewSource(time.Now().UnixNano()))
+	return cmd.runWritesWithSource(db, options, results, func() uint32 { return r.Uint32() })
+}
+
+func (cmd *BenchCommand) runWritesSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	var i = uint32(0)
+	return cmd.runWritesNestedWithSource(db, options, results, func() uint32 { i++; return i })
+}
+
+func (cmd *BenchCommand) runWritesRandomNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	r := rand.New(rand.NewSource(time.Now().UnixNano()))
+	return cmd.runWritesNestedWithSource(db, options, results, func() uint32 { return r.Uint32() })
+}
+
+func (cmd *BenchCommand) runWritesWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
+	results.WriteOps = options.Iterations
+
+	for i := 0; i < options.Iterations; i += options.BatchSize {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, _ := tx.CreateBucketIfNotExists(benchBucketName)
+			b.FillPercent = options.FillPercent
+
+			for j := 0; j < options.BatchSize; j++ {
+				key := make([]byte, options.KeySize)
+				value := make([]byte, options.ValueSize)
+
+				// Write key as uint32.
+				binary.BigEndian.PutUint32(key, keySource())
+
+				// Insert key/value.
+				if err := b.Put(key, value); err != nil {
+					return err
+				}
+			}
+
+			return nil
+		}); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func (cmd *BenchCommand) runWritesNestedWithSource(db *bolt.DB, options *BenchOptions, results *BenchResults, keySource func() uint32) error {
+	results.WriteOps = options.Iterations
+
+	for i := 0; i < options.Iterations; i += options.BatchSize {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			top, err := tx.CreateBucketIfNotExists(benchBucketName)
+			if err != nil {
+				return err
+			}
+			top.FillPercent = options.FillPercent
+
+			// Create bucket key.
+			name := make([]byte, options.KeySize)
+			binary.BigEndian.PutUint32(name, keySource())
+
+			// Create bucket.
+			b, err := top.CreateBucketIfNotExists(name)
+			if err != nil {
+				return err
+			}
+			b.FillPercent = options.FillPercent
+
+			for j := 0; j < options.BatchSize; j++ {
+				var key = make([]byte, options.KeySize)
+				var value = make([]byte, options.ValueSize)
+
+				// Generate key as uint32.
+				binary.BigEndian.PutUint32(key, keySource())
+
+				// Insert value into subbucket.
+				if err := b.Put(key, value); err != nil {
+					return err
+				}
+			}
+
+			return nil
+		}); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// Reads from the database.
+func (cmd *BenchCommand) runReads(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	// Start profiling for reads.
+	if options.ProfileMode == "r" {
+		cmd.startProfiling(options)
+	}
+
+	t := time.Now()
+
+	var err error
+	switch options.ReadMode {
+	case "seq":
+		switch options.WriteMode {
+		case "seq-nest", "rnd-nest":
+			err = cmd.runReadsSequentialNested(db, options, results)
+		default:
+			err = cmd.runReadsSequential(db, options, results)
+		}
+	default:
+		return fmt.Errorf("invalid read mode: %s", options.ReadMode)
+	}
+
+	// Save read time.
+	results.ReadDuration = time.Since(t)
+
+	// Stop profiling for reads.
+	if options.ProfileMode == "rw" || options.ProfileMode == "r" {
+		cmd.stopProfiling()
+	}
+
+	return err
+}
+
+func (cmd *BenchCommand) runReadsSequential(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	return db.View(func(tx *bolt.Tx) error {
+		t := time.Now()
+
+		for {
+			var count int
+
+			c := tx.Bucket(benchBucketName).Cursor()
+			for k, v := c.First(); k != nil; k, v = c.Next() {
+				if v == nil {
+					return errors.New("invalid value")
+				}
+				count++
+			}
+
+			if options.WriteMode == "seq" && count != options.Iterations {
+				return fmt.Errorf("read seq: iter mismatch: expected %d, got %d", options.Iterations, count)
+			}
+
+			results.ReadOps += count
+
+			// Make sure we do this for at least a second.
+			if time.Since(t) >= time.Second {
+				break
+			}
+		}
+
+		return nil
+	})
+}
+
+func (cmd *BenchCommand) runReadsSequentialNested(db *bolt.DB, options *BenchOptions, results *BenchResults) error {
+	return db.View(func(tx *bolt.Tx) error {
+		t := time.Now()
+
+		for {
+			var count int
+			var top = tx.Bucket(benchBucketName)
+			if err := top.ForEach(func(name, _ []byte) error {
+				if b := top.Bucket(name); b != nil {
+					c := b.Cursor()
+					for k, v := c.First(); k != nil; k, v = c.Next() {
+						if v == nil {
+							return ErrInvalidValue
+						}
+						count++
+					}
+				}
+				return nil
+			}); err != nil {
+				return err
+			}
+
+			if options.WriteMode == "seq-nest" && count != options.Iterations {
+				return fmt.Errorf("read seq-nest: iter mismatch: expected %d, got %d", options.Iterations, count)
+			}
+
+			results.ReadOps += count
+
+			// Make sure we do this for at least a second.
+			if time.Since(t) >= time.Second {
+				break
+			}
+		}
+
+		return nil
+	})
+}
+
+// File handlers for the various profiles.
+var cpuprofile, memprofile, blockprofile *os.File
+
+// Starts all profiles set on the options.
+func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
+	var err error
+
+	// Start CPU profiling.
+	if options.CPUProfile != "" {
+		cpuprofile, err = os.Create(options.CPUProfile)
+		if err != nil {
+			fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
+			os.Exit(1)
+		}
+		pprof.StartCPUProfile(cpuprofile)
+	}
+
+	// Start memory profiling.
+	if options.MemProfile != "" {
+		memprofile, err = os.Create(options.MemProfile)
+		if err != nil {
+			fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
+			os.Exit(1)
+		}
+		runtime.MemProfileRate = 4096
+	}
+
+	// Start fatal profiling.
+	if options.BlockProfile != "" {
+		blockprofile, err = os.Create(options.BlockProfile)
+		if err != nil {
+			fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
+			os.Exit(1)
+		}
+		runtime.SetBlockProfileRate(1)
+	}
+}
+
+// Stops all profiles.
+func (cmd *BenchCommand) stopProfiling() {
+	if cpuprofile != nil {
+		pprof.StopCPUProfile()
+		cpuprofile.Close()
+		cpuprofile = nil
+	}
+
+	if memprofile != nil {
+		pprof.Lookup("heap").WriteTo(memprofile, 0)
+		memprofile.Close()
+		memprofile = nil
+	}
+
+	if blockprofile != nil {
+		pprof.Lookup("block").WriteTo(blockprofile, 0)
+		blockprofile.Close()
+		blockprofile = nil
+		runtime.SetBlockProfileRate(0)
+	}
+}
+
+// BenchOptions represents the set of options that can be passed to "bolt bench".
+type BenchOptions struct {
+	ProfileMode   string
+	WriteMode     string
+	ReadMode      string
+	Iterations    int
+	BatchSize     int
+	KeySize       int
+	ValueSize     int
+	CPUProfile    string
+	MemProfile    string
+	BlockProfile  string
+	StatsInterval time.Duration
+	FillPercent   float64
+	NoSync        bool
+	Work          bool
+	Path          string
+}
+
+// BenchResults represents the performance results of the benchmark.
+type BenchResults struct {
+	WriteOps      int
+	WriteDuration time.Duration
+	ReadOps       int
+	ReadDuration  time.Duration
+}
+
+// Returns the duration for a single write operation.
+func (r *BenchResults) WriteOpDuration() time.Duration {
+	if r.WriteOps == 0 {
+		return 0
+	}
+	return r.WriteDuration / time.Duration(r.WriteOps)
+}
+
+// Returns average number of write operations that can be performed per second.
+func (r *BenchResults) WriteOpsPerSecond() int {
+	var op = r.WriteOpDuration()
+	if op == 0 {
+		return 0
+	}
+	return int(time.Second) / int(op)
+}
+
+// Returns the duration for a single read operation.
+func (r *BenchResults) ReadOpDuration() time.Duration {
+	if r.ReadOps == 0 {
+		return 0
+	}
+	return r.ReadDuration / time.Duration(r.ReadOps)
+}
+
+// Returns average number of read operations that can be performed per second.
+func (r *BenchResults) ReadOpsPerSecond() int {
+	var op = r.ReadOpDuration()
+	if op == 0 {
+		return 0
+	}
+	return int(time.Second) / int(op)
+}
+
+type PageError struct {
+	ID  int
+	Err error
+}
+
+func (e *PageError) Error() string {
+	return fmt.Sprintf("page error: id=%d, err=%s", e.ID, e.Err)
+}
+
+// isPrintable returns true if the string is valid unicode and contains only printable runes.
+func isPrintable(s string) bool {
+	if !utf8.ValidString(s) {
+		return false
+	}
+	for _, ch := range s {
+		if !unicode.IsPrint(ch) {
+			return false
+		}
+	}
+	return true
+}
+
+// ReadPage reads page info & full page data from a path.
+// This is not transactionally safe.
+func ReadPage(path string, pageID int) (*page, []byte, error) {
+	// Find page size.
+	pageSize, err := ReadPageSize(path)
+	if err != nil {
+		return nil, nil, fmt.Errorf("read page size: %s", err)
+	}
+
+	// Open database file.
+	f, err := os.Open(path)
+	if err != nil {
+		return nil, nil, err
+	}
+	defer f.Close()
+
+	// Read one block into buffer.
+	buf := make([]byte, pageSize)
+	if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
+		return nil, nil, err
+	} else if n != len(buf) {
+		return nil, nil, io.ErrUnexpectedEOF
+	}
+
+	// Determine total number of blocks.
+	p := (*page)(unsafe.Pointer(&buf[0]))
+	overflowN := p.overflow
+
+	// Re-read entire page (with overflow) into buffer.
+	buf = make([]byte, (int(overflowN)+1)*pageSize)
+	if n, err := f.ReadAt(buf, int64(pageID*pageSize)); err != nil {
+		return nil, nil, err
+	} else if n != len(buf) {
+		return nil, nil, io.ErrUnexpectedEOF
+	}
+	p = (*page)(unsafe.Pointer(&buf[0]))
+
+	return p, buf, nil
+}
+
+// ReadPageSize reads page size a path.
+// This is not transactionally safe.
+func ReadPageSize(path string) (int, error) {
+	// Open database file.
+	f, err := os.Open(path)
+	if err != nil {
+		return 0, err
+	}
+	defer f.Close()
+
+	// Read 4KB chunk.
+	buf := make([]byte, 4096)
+	if _, err := io.ReadFull(f, buf); err != nil {
+		return 0, err
+	}
+
+	// Read page size from metadata.
+	m := (*meta)(unsafe.Pointer(&buf[PageHeaderSize]))
+	return int(m.pageSize), nil
+}
+
+// atois parses a slice of strings into integers.
+func atois(strs []string) ([]int, error) {
+	var a []int
+	for _, str := range strs {
+		i, err := strconv.Atoi(str)
+		if err != nil {
+			return nil, err
+		}
+		a = append(a, i)
+	}
+	return a, nil
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+const maxAllocSize = 0xFFFFFFF
+
+// DO NOT EDIT. Copied from the "bolt" package.
+const (
+	branchPageFlag   = 0x01
+	leafPageFlag     = 0x02
+	metaPageFlag     = 0x04
+	freelistPageFlag = 0x10
+)
+
+// DO NOT EDIT. Copied from the "bolt" package.
+const bucketLeafFlag = 0x01
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type pgid uint64
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type txid uint64
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type meta struct {
+	magic    uint32
+	version  uint32
+	pageSize uint32
+	flags    uint32
+	root     bucket
+	freelist pgid
+	pgid     pgid
+	txid     txid
+	checksum uint64
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type bucket struct {
+	root     pgid
+	sequence uint64
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type page struct {
+	id       pgid
+	flags    uint16
+	count    uint16
+	overflow uint32
+	ptr      uintptr
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (p *page) Type() string {
+	if (p.flags & branchPageFlag) != 0 {
+		return "branch"
+	} else if (p.flags & leafPageFlag) != 0 {
+		return "leaf"
+	} else if (p.flags & metaPageFlag) != 0 {
+		return "meta"
+	} else if (p.flags & freelistPageFlag) != 0 {
+		return "freelist"
+	}
+	return fmt.Sprintf("unknown<%02x>", p.flags)
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (p *page) leafPageElement(index uint16) *leafPageElement {
+	n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
+	return n
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (p *page) branchPageElement(index uint16) *branchPageElement {
+	return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type branchPageElement struct {
+	pos   uint32
+	ksize uint32
+	pgid  pgid
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (n *branchPageElement) key() []byte {
+	buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+	return buf[n.pos : n.pos+n.ksize]
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+type leafPageElement struct {
+	flags uint32
+	pos   uint32
+	ksize uint32
+	vsize uint32
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (n *leafPageElement) key() []byte {
+	buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+	return buf[n.pos : n.pos+n.ksize]
+}
+
+// DO NOT EDIT. Copied from the "bolt" package.
+func (n *leafPageElement) value() []byte {
+	buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
+	return buf[n.pos+n.ksize : n.pos+n.ksize+n.vsize]
+}
+
+// CompactCommand represents the "compact" command execution.
+type CompactCommand struct {
+	Stdin  io.Reader
+	Stdout io.Writer
+	Stderr io.Writer
+
+	SrcPath   string
+	DstPath   string
+	TxMaxSize int64
+}
+
+// newCompactCommand returns a CompactCommand.
+func newCompactCommand(m *Main) *CompactCommand {
+	return &CompactCommand{
+		Stdin:  m.Stdin,
+		Stdout: m.Stdout,
+		Stderr: m.Stderr,
+	}
+}
+
+// Run executes the command.
+func (cmd *CompactCommand) Run(args ...string) (err error) {
+	// Parse flags.
+	fs := flag.NewFlagSet("", flag.ContinueOnError)
+	fs.SetOutput(ioutil.Discard)
+	fs.StringVar(&cmd.DstPath, "o", "", "")
+	fs.Int64Var(&cmd.TxMaxSize, "tx-max-size", 65536, "")
+	if err := fs.Parse(args); err == flag.ErrHelp {
+		fmt.Fprintln(cmd.Stderr, cmd.Usage())
+		return ErrUsage
+	} else if err != nil {
+		return err
+	} else if cmd.DstPath == "" {
+		return fmt.Errorf("output file required")
+	}
+
+	// Require database paths.
+	cmd.SrcPath = fs.Arg(0)
+	if cmd.SrcPath == "" {
+		return ErrPathRequired
+	}
+
+	// Ensure source file exists.
+	fi, err := os.Stat(cmd.SrcPath)
+	if os.IsNotExist(err) {
+		return ErrFileNotFound
+	} else if err != nil {
+		return err
+	}
+	initialSize := fi.Size()
+
+	// Open source database.
+	src, err := bolt.Open(cmd.SrcPath, 0444, nil)
+	if err != nil {
+		return err
+	}
+	defer src.Close()
+
+	// Open destination database.
+	dst, err := bolt.Open(cmd.DstPath, fi.Mode(), nil)
+	if err != nil {
+		return err
+	}
+	defer dst.Close()
+
+	// Run compaction.
+	if err := cmd.compact(dst, src); err != nil {
+		return err
+	}
+
+	// Report stats on new size.
+	fi, err = os.Stat(cmd.DstPath)
+	if err != nil {
+		return err
+	} else if fi.Size() == 0 {
+		return fmt.Errorf("zero db size")
+	}
+	fmt.Fprintf(cmd.Stdout, "%d -> %d bytes (gain=%.2fx)\n", initialSize, fi.Size(), float64(initialSize)/float64(fi.Size()))
+
+	return nil
+}
+
+func (cmd *CompactCommand) compact(dst, src *bolt.DB) error {
+	// commit regularly, or we'll run out of memory for large datasets if using one transaction.
+	var size int64
+	tx, err := dst.Begin(true)
+	if err != nil {
+		return err
+	}
+	defer tx.Rollback()
+
+	if err := cmd.walk(src, func(keys [][]byte, k, v []byte, seq uint64) error {
+		// On each key/value, check if we have exceeded tx size.
+		sz := int64(len(k) + len(v))
+		if size+sz > cmd.TxMaxSize && cmd.TxMaxSize != 0 {
+			// Commit previous transaction.
+			if err := tx.Commit(); err != nil {
+				return err
+			}
+
+			// Start new transaction.
+			tx, err = dst.Begin(true)
+			if err != nil {
+				return err
+			}
+			size = 0
+		}
+		size += sz
+
+		// Create bucket on the root transaction if this is the first level.
+		nk := len(keys)
+		if nk == 0 {
+			bkt, err := tx.CreateBucket(k)
+			if err != nil {
+				return err
+			}
+			if err := bkt.SetSequence(seq); err != nil {
+				return err
+			}
+			return nil
+		}
+
+		// Create buckets on subsequent levels, if necessary.
+		b := tx.Bucket(keys[0])
+		if nk > 1 {
+			for _, k := range keys[1:] {
+				b = b.Bucket(k)
+			}
+		}
+
+		// Fill the entire page for best compaction.
+		b.FillPercent = 1.0
+
+		// If there is no value then this is a bucket call.
+		if v == nil {
+			bkt, err := b.CreateBucket(k)
+			if err != nil {
+				return err
+			}
+			if err := bkt.SetSequence(seq); err != nil {
+				return err
+			}
+			return nil
+		}
+
+		// Otherwise treat it as a key/value pair.
+		return b.Put(k, v)
+	}); err != nil {
+		return err
+	}
+
+	return tx.Commit()
+}
+
+// walkFunc is the type of the function called for keys (buckets and "normal"
+// values) discovered by Walk. keys is the list of keys to descend to the bucket
+// owning the discovered key/value pair k/v.
+type walkFunc func(keys [][]byte, k, v []byte, seq uint64) error
+
+// walk walks recursively the bolt database db, calling walkFn for each key it finds.
+func (cmd *CompactCommand) walk(db *bolt.DB, walkFn walkFunc) error {
+	return db.View(func(tx *bolt.Tx) error {
+		return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
+			return cmd.walkBucket(b, nil, name, nil, b.Sequence(), walkFn)
+		})
+	})
+}
+
+func (cmd *CompactCommand) walkBucket(b *bolt.Bucket, keypath [][]byte, k, v []byte, seq uint64, fn walkFunc) error {
+	// Execute callback.
+	if err := fn(keypath, k, v, seq); err != nil {
+		return err
+	}
+
+	// If this is not a bucket then stop.
+	if v != nil {
+		return nil
+	}
+
+	// Iterate over each child key/value.
+	keypath = append(keypath, k)
+	return b.ForEach(func(k, v []byte) error {
+		if v == nil {
+			bkt := b.Bucket(k)
+			return cmd.walkBucket(bkt, keypath, k, nil, bkt.Sequence(), fn)
+		}
+		return cmd.walkBucket(b, keypath, k, v, b.Sequence(), fn)
+	})
+}
+
+// Usage returns the help message.
+func (cmd *CompactCommand) Usage() string {
+	return strings.TrimLeft(`
+usage: bolt compact [options] -o DST SRC
+
+Compact opens a database at SRC path and walks it recursively, copying keys
+as they are found from all buckets, to a newly created database at DST path.
+
+The original database is left untouched.
+
+Additional options include:
+
+	-tx-max-size NUM
+		Specifies the maximum size of individual transactions.
+		Defaults to 64KB.
+`, "\n")
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go b/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go
new file mode 100644
index 000000000..16bf804ae
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/cmd/bolt/main_test.go
@@ -0,0 +1,456 @@
+package main_test
+
+import (
+	"bytes"
+	crypto "crypto/rand"
+	"encoding/binary"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"math/rand"
+	"os"
+	"strconv"
+	"testing"
+
+	"github.com/coreos/bbolt"
+	"github.com/coreos/bbolt/cmd/bolt"
+)
+
+// Ensure the "info" command can print information about a database.
+func TestInfoCommand_Run(t *testing.T) {
+	db := MustOpen(0666, nil)
+	db.DB.Close()
+	defer db.Close()
+
+	// Run the info command.
+	m := NewMain()
+	if err := m.Run("info", db.Path); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure the "stats" command executes correctly with an empty database.
+func TestStatsCommand_Run_EmptyDatabase(t *testing.T) {
+	// Ignore
+	if os.Getpagesize() != 4096 {
+		t.Skip("system does not use 4KB page size")
+	}
+
+	db := MustOpen(0666, nil)
+	defer db.Close()
+	db.DB.Close()
+
+	// Generate expected result.
+	exp := "Aggregate statistics for 0 buckets\n\n" +
+		"Page count statistics\n" +
+		"\tNumber of logical branch pages: 0\n" +
+		"\tNumber of physical branch overflow pages: 0\n" +
+		"\tNumber of logical leaf pages: 0\n" +
+		"\tNumber of physical leaf overflow pages: 0\n" +
+		"Tree statistics\n" +
+		"\tNumber of keys/value pairs: 0\n" +
+		"\tNumber of levels in B+tree: 0\n" +
+		"Page size utilization\n" +
+		"\tBytes allocated for physical branch pages: 0\n" +
+		"\tBytes actually used for branch data: 0 (0%)\n" +
+		"\tBytes allocated for physical leaf pages: 0\n" +
+		"\tBytes actually used for leaf data: 0 (0%)\n" +
+		"Bucket statistics\n" +
+		"\tTotal number of buckets: 0\n" +
+		"\tTotal number on inlined buckets: 0 (0%)\n" +
+		"\tBytes used for inlined buckets: 0 (0%)\n"
+
+	// Run the command.
+	m := NewMain()
+	if err := m.Run("stats", db.Path); err != nil {
+		t.Fatal(err)
+	} else if m.Stdout.String() != exp {
+		t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String())
+	}
+}
+
+// Ensure the "stats" command can execute correctly.
+func TestStatsCommand_Run(t *testing.T) {
+	// Ignore
+	if os.Getpagesize() != 4096 {
+		t.Skip("system does not use 4KB page size")
+	}
+
+	db := MustOpen(0666, nil)
+	defer db.Close()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create "foo" bucket.
+		b, err := tx.CreateBucket([]byte("foo"))
+		if err != nil {
+			return err
+		}
+		for i := 0; i < 10; i++ {
+			if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
+				return err
+			}
+		}
+
+		// Create "bar" bucket.
+		b, err = tx.CreateBucket([]byte("bar"))
+		if err != nil {
+			return err
+		}
+		for i := 0; i < 100; i++ {
+			if err := b.Put([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i))); err != nil {
+				return err
+			}
+		}
+
+		// Create "baz" bucket.
+		b, err = tx.CreateBucket([]byte("baz"))
+		if err != nil {
+			return err
+		}
+		if err := b.Put([]byte("key"), []byte("value")); err != nil {
+			return err
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.DB.Close()
+
+	// Generate expected result.
+	exp := "Aggregate statistics for 3 buckets\n\n" +
+		"Page count statistics\n" +
+		"\tNumber of logical branch pages: 0\n" +
+		"\tNumber of physical branch overflow pages: 0\n" +
+		"\tNumber of logical leaf pages: 1\n" +
+		"\tNumber of physical leaf overflow pages: 0\n" +
+		"Tree statistics\n" +
+		"\tNumber of keys/value pairs: 111\n" +
+		"\tNumber of levels in B+tree: 1\n" +
+		"Page size utilization\n" +
+		"\tBytes allocated for physical branch pages: 0\n" +
+		"\tBytes actually used for branch data: 0 (0%)\n" +
+		"\tBytes allocated for physical leaf pages: 4096\n" +
+		"\tBytes actually used for leaf data: 1996 (48%)\n" +
+		"Bucket statistics\n" +
+		"\tTotal number of buckets: 3\n" +
+		"\tTotal number on inlined buckets: 2 (66%)\n" +
+		"\tBytes used for inlined buckets: 236 (11%)\n"
+
+	// Run the command.
+	m := NewMain()
+	if err := m.Run("stats", db.Path); err != nil {
+		t.Fatal(err)
+	} else if m.Stdout.String() != exp {
+		t.Fatalf("unexpected stdout:\n\n%s", m.Stdout.String())
+	}
+}
+
+// Ensure the "buckets" command can print a list of buckets.
+func TestBucketsCommand_Run(t *testing.T) {
+	db := MustOpen(0666, nil)
+	defer db.Close()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		for _, name := range []string{"foo", "bar", "baz"} {
+			_, err := tx.CreateBucket([]byte(name))
+			if err != nil {
+				return err
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.DB.Close()
+
+	expected := "bar\nbaz\nfoo\n"
+
+	// Run the command.
+	m := NewMain()
+	if err := m.Run("buckets", db.Path); err != nil {
+		t.Fatal(err)
+	} else if actual := m.Stdout.String(); actual != expected {
+		t.Fatalf("unexpected stdout:\n\n%s", actual)
+	}
+}
+
+// Ensure the "keys" command can print a list of keys for a bucket.
+func TestKeysCommand_Run(t *testing.T) {
+	db := MustOpen(0666, nil)
+	defer db.Close()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		for _, name := range []string{"foo", "bar"} {
+			b, err := tx.CreateBucket([]byte(name))
+			if err != nil {
+				return err
+			}
+			for i := 0; i < 3; i++ {
+				key := fmt.Sprintf("%s-%d", name, i)
+				if err := b.Put([]byte(key), []byte{0}); err != nil {
+					return err
+				}
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.DB.Close()
+
+	expected := "foo-0\nfoo-1\nfoo-2\n"
+
+	// Run the command.
+	m := NewMain()
+	if err := m.Run("keys", db.Path, "foo"); err != nil {
+		t.Fatal(err)
+	} else if actual := m.Stdout.String(); actual != expected {
+		t.Fatalf("unexpected stdout:\n\n%s", actual)
+	}
+}
+
+// Ensure the "get" command can print the value of a key in a bucket.
+func TestGetCommand_Run(t *testing.T) {
+	db := MustOpen(0666, nil)
+	defer db.Close()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		for _, name := range []string{"foo", "bar"} {
+			b, err := tx.CreateBucket([]byte(name))
+			if err != nil {
+				return err
+			}
+			for i := 0; i < 3; i++ {
+				key := fmt.Sprintf("%s-%d", name, i)
+				val := fmt.Sprintf("val-%s-%d", name, i)
+				if err := b.Put([]byte(key), []byte(val)); err != nil {
+					return err
+				}
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	db.DB.Close()
+
+	expected := "val-foo-1\n"
+
+	// Run the command.
+	m := NewMain()
+	if err := m.Run("get", db.Path, "foo", "foo-1"); err != nil {
+		t.Fatal(err)
+	} else if actual := m.Stdout.String(); actual != expected {
+		t.Fatalf("unexpected stdout:\n\n%s", actual)
+	}
+}
+
+// Main represents a test wrapper for main.Main that records output.
+type Main struct {
+	*main.Main
+	Stdin  bytes.Buffer
+	Stdout bytes.Buffer
+	Stderr bytes.Buffer
+}
+
+// NewMain returns a new instance of Main.
+func NewMain() *Main {
+	m := &Main{Main: main.NewMain()}
+	m.Main.Stdin = &m.Stdin
+	m.Main.Stdout = &m.Stdout
+	m.Main.Stderr = &m.Stderr
+	return m
+}
+
+// MustOpen creates a Bolt database in a temporary location.
+func MustOpen(mode os.FileMode, options *bolt.Options) *DB {
+	// Create temporary path.
+	f, _ := ioutil.TempFile("", "bolt-")
+	f.Close()
+	os.Remove(f.Name())
+
+	db, err := bolt.Open(f.Name(), mode, options)
+	if err != nil {
+		panic(err.Error())
+	}
+	return &DB{DB: db, Path: f.Name()}
+}
+
+// DB is a test wrapper for bolt.DB.
+type DB struct {
+	*bolt.DB
+	Path string
+}
+
+// Close closes and removes the database.
+func (db *DB) Close() error {
+	defer os.Remove(db.Path)
+	return db.DB.Close()
+}
+
+func TestCompactCommand_Run(t *testing.T) {
+	var s int64
+	if err := binary.Read(crypto.Reader, binary.BigEndian, &s); err != nil {
+		t.Fatal(err)
+	}
+	rand.Seed(s)
+
+	dstdb := MustOpen(0666, nil)
+	dstdb.Close()
+
+	// fill the db
+	db := MustOpen(0666, nil)
+	if err := db.Update(func(tx *bolt.Tx) error {
+		n := 2 + rand.Intn(5)
+		for i := 0; i < n; i++ {
+			k := []byte(fmt.Sprintf("b%d", i))
+			b, err := tx.CreateBucketIfNotExists(k)
+			if err != nil {
+				return err
+			}
+			if err := b.SetSequence(uint64(i)); err != nil {
+				return err
+			}
+			if err := fillBucket(b, append(k, '.')); err != nil {
+				return err
+			}
+		}
+		return nil
+	}); err != nil {
+		db.Close()
+		t.Fatal(err)
+	}
+
+	// make the db grow by adding large values, and delete them.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucketIfNotExists([]byte("large_vals"))
+		if err != nil {
+			return err
+		}
+		n := 5 + rand.Intn(5)
+		for i := 0; i < n; i++ {
+			v := make([]byte, 1000*1000*(1+rand.Intn(5)))
+			_, err := crypto.Read(v)
+			if err != nil {
+				return err
+			}
+			if err := b.Put([]byte(fmt.Sprintf("l%d", i)), v); err != nil {
+				return err
+			}
+		}
+		return nil
+	}); err != nil {
+		db.Close()
+		t.Fatal(err)
+	}
+	if err := db.Update(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("large_vals")).Cursor()
+		for k, _ := c.First(); k != nil; k, _ = c.Next() {
+			if err := c.Delete(); err != nil {
+				return err
+			}
+		}
+		return tx.DeleteBucket([]byte("large_vals"))
+	}); err != nil {
+		db.Close()
+		t.Fatal(err)
+	}
+	db.DB.Close()
+	defer db.Close()
+	defer dstdb.Close()
+
+	dbChk, err := chkdb(db.Path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	m := NewMain()
+	if err := m.Run("compact", "-o", dstdb.Path, db.Path); err != nil {
+		t.Fatal(err)
+	}
+
+	dbChkAfterCompact, err := chkdb(db.Path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	dstdbChk, err := chkdb(dstdb.Path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if !bytes.Equal(dbChk, dbChkAfterCompact) {
+		t.Error("the original db has been touched")
+	}
+	if !bytes.Equal(dbChk, dstdbChk) {
+		t.Error("the compacted db data isn't the same than the original db")
+	}
+}
+
+func fillBucket(b *bolt.Bucket, prefix []byte) error {
+	n := 10 + rand.Intn(50)
+	for i := 0; i < n; i++ {
+		v := make([]byte, 10*(1+rand.Intn(4)))
+		_, err := crypto.Read(v)
+		if err != nil {
+			return err
+		}
+		k := append(prefix, []byte(fmt.Sprintf("k%d", i))...)
+		if err := b.Put(k, v); err != nil {
+			return err
+		}
+	}
+	// limit depth of subbuckets
+	s := 2 + rand.Intn(4)
+	if len(prefix) > (2*s + 1) {
+		return nil
+	}
+	n = 1 + rand.Intn(3)
+	for i := 0; i < n; i++ {
+		k := append(prefix, []byte(fmt.Sprintf("b%d", i))...)
+		sb, err := b.CreateBucket(k)
+		if err != nil {
+			return err
+		}
+		if err := fillBucket(sb, append(k, '.')); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func chkdb(path string) ([]byte, error) {
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		return nil, err
+	}
+	defer db.Close()
+	var buf bytes.Buffer
+	err = db.View(func(tx *bolt.Tx) error {
+		return tx.ForEach(func(name []byte, b *bolt.Bucket) error {
+			return walkBucket(b, name, nil, &buf)
+		})
+	})
+	if err != nil {
+		return nil, err
+	}
+	return buf.Bytes(), nil
+}
+
+func walkBucket(parent *bolt.Bucket, k []byte, v []byte, w io.Writer) error {
+	if _, err := fmt.Fprintf(w, "%d:%x=%x\n", parent.Sequence(), k, v); err != nil {
+		return err
+	}
+
+	// not a bucket, exit.
+	if v != nil {
+		return nil
+	}
+	return parent.ForEach(func(k, v []byte) error {
+		if v == nil {
+			return walkBucket(parent.Bucket(k), k, nil, w)
+		}
+		return walkBucket(parent, k, v, w)
+	})
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/cursor.go b/grove/vendor/github.com/coreos/bbolt/cursor.go
new file mode 100644
index 000000000..1be9f35e3
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/cursor.go
@@ -0,0 +1,400 @@
+package bolt
+
+import (
+	"bytes"
+	"fmt"
+	"sort"
+)
+
+// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order.
+// Cursors see nested buckets with value == nil.
+// Cursors can be obtained from a transaction and are valid as long as the transaction is open.
+//
+// Keys and values returned from the cursor are only valid for the life of the transaction.
+//
+// Changing data while traversing with a cursor may cause it to be invalidated
+// and return unexpected keys and/or values. You must reposition your cursor
+// after mutating data.
+type Cursor struct {
+	bucket *Bucket
+	stack  []elemRef
+}
+
+// Bucket returns the bucket that this cursor was created from.
+func (c *Cursor) Bucket() *Bucket {
+	return c.bucket
+}
+
+// First moves the cursor to the first item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) First() (key []byte, value []byte) {
+	_assert(c.bucket.tx.db != nil, "tx closed")
+	c.stack = c.stack[:0]
+	p, n := c.bucket.pageNode(c.bucket.root)
+	c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+	c.first()
+
+	// If we land on an empty page then move to the next value.
+	// https://github.com/boltdb/bolt/issues/450
+	if c.stack[len(c.stack)-1].count() == 0 {
+		c.next()
+	}
+
+	k, v, flags := c.keyValue()
+	if (flags & uint32(bucketLeafFlag)) != 0 {
+		return k, nil
+	}
+	return k, v
+
+}
+
+// Last moves the cursor to the last item in the bucket and returns its key and value.
+// If the bucket is empty then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Last() (key []byte, value []byte) {
+	_assert(c.bucket.tx.db != nil, "tx closed")
+	c.stack = c.stack[:0]
+	p, n := c.bucket.pageNode(c.bucket.root)
+	ref := elemRef{page: p, node: n}
+	ref.index = ref.count() - 1
+	c.stack = append(c.stack, ref)
+	c.last()
+	k, v, flags := c.keyValue()
+	if (flags & uint32(bucketLeafFlag)) != 0 {
+		return k, nil
+	}
+	return k, v
+}
+
+// Next moves the cursor to the next item in the bucket and returns its key and value.
+// If the cursor is at the end of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Next() (key []byte, value []byte) {
+	_assert(c.bucket.tx.db != nil, "tx closed")
+	k, v, flags := c.next()
+	if (flags & uint32(bucketLeafFlag)) != 0 {
+		return k, nil
+	}
+	return k, v
+}
+
+// Prev moves the cursor to the previous item in the bucket and returns its key and value.
+// If the cursor is at the beginning of the bucket then a nil key and value are returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Prev() (key []byte, value []byte) {
+	_assert(c.bucket.tx.db != nil, "tx closed")
+
+	// Attempt to move back one element until we're successful.
+	// Move up the stack as we hit the beginning of each page in our stack.
+	for i := len(c.stack) - 1; i >= 0; i-- {
+		elem := &c.stack[i]
+		if elem.index > 0 {
+			elem.index--
+			break
+		}
+		c.stack = c.stack[:i]
+	}
+
+	// If we've hit the end then return nil.
+	if len(c.stack) == 0 {
+		return nil, nil
+	}
+
+	// Move down the stack to find the last element of the last leaf under this branch.
+	c.last()
+	k, v, flags := c.keyValue()
+	if (flags & uint32(bucketLeafFlag)) != 0 {
+		return k, nil
+	}
+	return k, v
+}
+
+// Seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used. If no keys
+// follow, a nil key is returned.
+// The returned key and value are only valid for the life of the transaction.
+func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
+	k, v, flags := c.seek(seek)
+
+	// If we ended up after the last element of a page then move to the next one.
+	if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() {
+		k, v, flags = c.next()
+	}
+
+	if k == nil {
+		return nil, nil
+	} else if (flags & uint32(bucketLeafFlag)) != 0 {
+		return k, nil
+	}
+	return k, v
+}
+
+// Delete removes the current key/value under the cursor from the bucket.
+// Delete fails if current key/value is a bucket or if the transaction is not writable.
+func (c *Cursor) Delete() error {
+	if c.bucket.tx.db == nil {
+		return ErrTxClosed
+	} else if !c.bucket.Writable() {
+		return ErrTxNotWritable
+	}
+
+	key, _, flags := c.keyValue()
+	// Return an error if current value is a bucket.
+	if (flags & bucketLeafFlag) != 0 {
+		return ErrIncompatibleValue
+	}
+	c.node().del(key)
+
+	return nil
+}
+
+// seek moves the cursor to a given key and returns it.
+// If the key does not exist then the next key is used.
+func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) {
+	_assert(c.bucket.tx.db != nil, "tx closed")
+
+	// Start from root page/node and traverse to correct page.
+	c.stack = c.stack[:0]
+	c.search(seek, c.bucket.root)
+	ref := &c.stack[len(c.stack)-1]
+
+	// If the cursor is pointing to the end of page/node then return nil.
+	if ref.index >= ref.count() {
+		return nil, nil, 0
+	}
+
+	// If this is a bucket then return a nil value.
+	return c.keyValue()
+}
+
+// first moves the cursor to the first leaf element under the last page in the stack.
+func (c *Cursor) first() {
+	for {
+		// Exit when we hit a leaf page.
+		var ref = &c.stack[len(c.stack)-1]
+		if ref.isLeaf() {
+			break
+		}
+
+		// Keep adding pages pointing to the first element to the stack.
+		var pgid pgid
+		if ref.node != nil {
+			pgid = ref.node.inodes[ref.index].pgid
+		} else {
+			pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+		}
+		p, n := c.bucket.pageNode(pgid)
+		c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
+	}
+}
+
+// last moves the cursor to the last leaf element under the last page in the stack.
+func (c *Cursor) last() {
+	for {
+		// Exit when we hit a leaf page.
+		ref := &c.stack[len(c.stack)-1]
+		if ref.isLeaf() {
+			break
+		}
+
+		// Keep adding pages pointing to the last element in the stack.
+		var pgid pgid
+		if ref.node != nil {
+			pgid = ref.node.inodes[ref.index].pgid
+		} else {
+			pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
+		}
+		p, n := c.bucket.pageNode(pgid)
+
+		var nextRef = elemRef{page: p, node: n}
+		nextRef.index = nextRef.count() - 1
+		c.stack = append(c.stack, nextRef)
+	}
+}
+
+// next moves to the next leaf element and returns the key and value.
+// If the cursor is at the last leaf element then it stays there and returns nil.
+func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
+	for {
+		// Attempt to move over one element until we're successful.
+		// Move up the stack as we hit the end of each page in our stack.
+		var i int
+		for i = len(c.stack) - 1; i >= 0; i-- {
+			elem := &c.stack[i]
+			if elem.index < elem.count()-1 {
+				elem.index++
+				break
+			}
+		}
+
+		// If we've hit the root page then stop and return. This will leave the
+		// cursor on the last element of the last page.
+		if i == -1 {
+			return nil, nil, 0
+		}
+
+		// Otherwise start from where we left off in the stack and find the
+		// first element of the first leaf page.
+		c.stack = c.stack[:i+1]
+		c.first()
+
+		// If this is an empty page then restart and move back up the stack.
+		// https://github.com/boltdb/bolt/issues/450
+		if c.stack[len(c.stack)-1].count() == 0 {
+			continue
+		}
+
+		return c.keyValue()
+	}
+}
+
+// search recursively performs a binary search against a given page/node until it finds a given key.
+func (c *Cursor) search(key []byte, pgid pgid) {
+	p, n := c.bucket.pageNode(pgid)
+	if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
+		panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
+	}
+	e := elemRef{page: p, node: n}
+	c.stack = append(c.stack, e)
+
+	// If we're on a leaf page/node then find the specific node.
+	if e.isLeaf() {
+		c.nsearch(key)
+		return
+	}
+
+	if n != nil {
+		c.searchNode(key, n)
+		return
+	}
+	c.searchPage(key, p)
+}
+
+func (c *Cursor) searchNode(key []byte, n *node) {
+	var exact bool
+	index := sort.Search(len(n.inodes), func(i int) bool {
+		// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+		// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+		ret := bytes.Compare(n.inodes[i].key, key)
+		if ret == 0 {
+			exact = true
+		}
+		return ret != -1
+	})
+	if !exact && index > 0 {
+		index--
+	}
+	c.stack[len(c.stack)-1].index = index
+
+	// Recursively search to the next page.
+	c.search(key, n.inodes[index].pgid)
+}
+
+func (c *Cursor) searchPage(key []byte, p *page) {
+	// Binary search for the correct range.
+	inodes := p.branchPageElements()
+
+	var exact bool
+	index := sort.Search(int(p.count), func(i int) bool {
+		// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
+		// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
+		ret := bytes.Compare(inodes[i].key(), key)
+		if ret == 0 {
+			exact = true
+		}
+		return ret != -1
+	})
+	if !exact && index > 0 {
+		index--
+	}
+	c.stack[len(c.stack)-1].index = index
+
+	// Recursively search to the next page.
+	c.search(key, inodes[index].pgid)
+}
+
+// nsearch searches the leaf node on the top of the stack for a key.
+func (c *Cursor) nsearch(key []byte) {
+	e := &c.stack[len(c.stack)-1]
+	p, n := e.page, e.node
+
+	// If we have a node then search its inodes.
+	if n != nil {
+		index := sort.Search(len(n.inodes), func(i int) bool {
+			return bytes.Compare(n.inodes[i].key, key) != -1
+		})
+		e.index = index
+		return
+	}
+
+	// If we have a page then search its leaf elements.
+	inodes := p.leafPageElements()
+	index := sort.Search(int(p.count), func(i int) bool {
+		return bytes.Compare(inodes[i].key(), key) != -1
+	})
+	e.index = index
+}
+
+// keyValue returns the key and value of the current leaf element.
+func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
+	ref := &c.stack[len(c.stack)-1]
+	if ref.count() == 0 || ref.index >= ref.count() {
+		return nil, nil, 0
+	}
+
+	// Retrieve value from node.
+	if ref.node != nil {
+		inode := &ref.node.inodes[ref.index]
+		return inode.key, inode.value, inode.flags
+	}
+
+	// Or retrieve value from page.
+	elem := ref.page.leafPageElement(uint16(ref.index))
+	return elem.key(), elem.value(), elem.flags
+}
+
+// node returns the node that the cursor is currently positioned on.
+func (c *Cursor) node() *node {
+	_assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
+
+	// If the top of the stack is a leaf node then just return it.
+	if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() {
+		return ref.node
+	}
+
+	// Start from root and traverse down the hierarchy.
+	var n = c.stack[0].node
+	if n == nil {
+		n = c.bucket.node(c.stack[0].page.id, nil)
+	}
+	for _, ref := range c.stack[:len(c.stack)-1] {
+		_assert(!n.isLeaf, "expected branch node")
+		n = n.childAt(int(ref.index))
+	}
+	_assert(n.isLeaf, "expected leaf node")
+	return n
+}
+
+// elemRef represents a reference to an element on a given page/node.
+type elemRef struct {
+	page  *page
+	node  *node
+	index int
+}
+
+// isLeaf returns whether the ref is pointing at a leaf page/node.
+func (r *elemRef) isLeaf() bool {
+	if r.node != nil {
+		return r.node.isLeaf
+	}
+	return (r.page.flags & leafPageFlag) != 0
+}
+
+// count returns the number of inodes or page elements.
+func (r *elemRef) count() int {
+	if r.node != nil {
+		return len(r.node.inodes)
+	}
+	return int(r.page.count)
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/cursor_test.go b/grove/vendor/github.com/coreos/bbolt/cursor_test.go
new file mode 100644
index 000000000..7b1ae1983
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/cursor_test.go
@@ -0,0 +1,817 @@
+package bolt_test
+
+import (
+	"bytes"
+	"encoding/binary"
+	"fmt"
+	"log"
+	"os"
+	"reflect"
+	"sort"
+	"testing"
+	"testing/quick"
+
+	"github.com/coreos/bbolt"
+)
+
+// Ensure that a cursor can return a reference to the bucket that created it.
+func TestCursor_Bucket(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if cb := b.Cursor().Bucket(); !reflect.DeepEqual(cb, b) {
+			t.Fatal("cursor bucket mismatch")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can seek to the appropriate keys.
+func TestCursor_Seek(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("0001")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte("0002")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte("0003")); err != nil {
+			t.Fatal(err)
+		}
+
+		if _, err := b.CreateBucket([]byte("bkt")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("widgets")).Cursor()
+
+		// Exact match should go to the key.
+		if k, v := c.Seek([]byte("bar")); !bytes.Equal(k, []byte("bar")) {
+			t.Fatalf("unexpected key: %v", k)
+		} else if !bytes.Equal(v, []byte("0002")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+
+		// Inexact match should go to the next key.
+		if k, v := c.Seek([]byte("bas")); !bytes.Equal(k, []byte("baz")) {
+			t.Fatalf("unexpected key: %v", k)
+		} else if !bytes.Equal(v, []byte("0003")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+
+		// Low key should go to the first key.
+		if k, v := c.Seek([]byte("")); !bytes.Equal(k, []byte("bar")) {
+			t.Fatalf("unexpected key: %v", k)
+		} else if !bytes.Equal(v, []byte("0002")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+
+		// High key should return no key.
+		if k, v := c.Seek([]byte("zzz")); k != nil {
+			t.Fatalf("expected nil key: %v", k)
+		} else if v != nil {
+			t.Fatalf("expected nil value: %v", v)
+		}
+
+		// Buckets should return their key but no value.
+		if k, v := c.Seek([]byte("bkt")); !bytes.Equal(k, []byte("bkt")) {
+			t.Fatalf("unexpected key: %v", k)
+		} else if v != nil {
+			t.Fatalf("expected nil value: %v", v)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestCursor_Delete(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	const count = 1000
+
+	// Insert every other key between 0 and $count.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for i := 0; i < count; i += 1 {
+			k := make([]byte, 8)
+			binary.BigEndian.PutUint64(k, uint64(i))
+			if err := b.Put(k, make([]byte, 100)); err != nil {
+				t.Fatal(err)
+			}
+		}
+		if _, err := b.CreateBucket([]byte("sub")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		bound := make([]byte, 8)
+		binary.BigEndian.PutUint64(bound, uint64(count/2))
+		for key, _ := c.First(); bytes.Compare(key, bound) < 0; key, _ = c.Next() {
+			if err := c.Delete(); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		c.Seek([]byte("sub"))
+		if err := c.Delete(); err != bolt.ErrIncompatibleValue {
+			t.Fatalf("unexpected error: %s", err)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		stats := tx.Bucket([]byte("widgets")).Stats()
+		if stats.KeyN != count/2+1 {
+			t.Fatalf("unexpected KeyN: %d", stats.KeyN)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can seek to the appropriate keys when there are a
+// large number of keys. This test also checks that seek will always move
+// forward to the next key.
+//
+// Related: https://github.com/boltdb/bolt/pull/187
+func TestCursor_Seek_Large(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var count = 10000
+
+	// Insert every other key between 0 and $count.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		for i := 0; i < count; i += 100 {
+			for j := i; j < i+100; j += 2 {
+				k := make([]byte, 8)
+				binary.BigEndian.PutUint64(k, uint64(j))
+				if err := b.Put(k, make([]byte, 100)); err != nil {
+					t.Fatal(err)
+				}
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		for i := 0; i < count; i++ {
+			seek := make([]byte, 8)
+			binary.BigEndian.PutUint64(seek, uint64(i))
+
+			k, _ := c.Seek(seek)
+
+			// The last seek is beyond the end of the the range so
+			// it should return nil.
+			if i == count-1 {
+				if k != nil {
+					t.Fatal("expected nil key")
+				}
+				continue
+			}
+
+			// Otherwise we should seek to the exact key or the next key.
+			num := binary.BigEndian.Uint64(k)
+			if i%2 == 0 {
+				if num != uint64(i) {
+					t.Fatalf("unexpected num: %d", num)
+				}
+			} else {
+				if num != uint64(i+1) {
+					t.Fatalf("unexpected num: %d", num)
+				}
+			}
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a cursor can iterate over an empty bucket without error.
+func TestCursor_EmptyBucket(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		_, err := tx.CreateBucket([]byte("widgets"))
+		return err
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		k, v := c.First()
+		if k != nil {
+			t.Fatalf("unexpected key: %v", k)
+		} else if v != nil {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can reverse iterate over an empty bucket without error.
+func TestCursor_EmptyBucketReverse(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		_, err := tx.CreateBucket([]byte("widgets"))
+		return err
+	}); err != nil {
+		t.Fatal(err)
+	}
+	if err := db.View(func(tx *bolt.Tx) error {
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		k, v := c.Last()
+		if k != nil {
+			t.Fatalf("unexpected key: %v", k)
+		} else if v != nil {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can iterate over a single root with a couple elements.
+func TestCursor_Iterate_Leaf(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte{}); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte{0}); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte{1}); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	tx, err := db.Begin(false)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer func() { _ = tx.Rollback() }()
+
+	c := tx.Bucket([]byte("widgets")).Cursor()
+
+	k, v := c.First()
+	if !bytes.Equal(k, []byte("bar")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{1}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	k, v = c.Next()
+	if !bytes.Equal(k, []byte("baz")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	k, v = c.Next()
+	if !bytes.Equal(k, []byte("foo")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{0}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	k, v = c.Next()
+	if k != nil {
+		t.Fatalf("expected nil key: %v", k)
+	} else if v != nil {
+		t.Fatalf("expected nil value: %v", v)
+	}
+
+	k, v = c.Next()
+	if k != nil {
+		t.Fatalf("expected nil key: %v", k)
+	} else if v != nil {
+		t.Fatalf("expected nil value: %v", v)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can iterate in reverse over a single root with a couple elements.
+func TestCursor_LeafRootReverse(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte{}); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte{0}); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte{1}); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	tx, err := db.Begin(false)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c := tx.Bucket([]byte("widgets")).Cursor()
+
+	if k, v := c.Last(); !bytes.Equal(k, []byte("foo")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{0}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	if k, v := c.Prev(); !bytes.Equal(k, []byte("baz")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	if k, v := c.Prev(); !bytes.Equal(k, []byte("bar")) {
+		t.Fatalf("unexpected key: %v", k)
+	} else if !bytes.Equal(v, []byte{1}) {
+		t.Fatalf("unexpected value: %v", v)
+	}
+
+	if k, v := c.Prev(); k != nil {
+		t.Fatalf("expected nil key: %v", k)
+	} else if v != nil {
+		t.Fatalf("expected nil value: %v", v)
+	}
+
+	if k, v := c.Prev(); k != nil {
+		t.Fatalf("expected nil key: %v", k)
+	} else if v != nil {
+		t.Fatalf("expected nil value: %v", v)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can restart from the beginning.
+func TestCursor_Restart(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("bar"), []byte{}); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte{}); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	tx, err := db.Begin(false)
+	if err != nil {
+		t.Fatal(err)
+	}
+	c := tx.Bucket([]byte("widgets")).Cursor()
+
+	if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) {
+		t.Fatalf("unexpected key: %v", k)
+	}
+	if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) {
+		t.Fatalf("unexpected key: %v", k)
+	}
+
+	if k, _ := c.First(); !bytes.Equal(k, []byte("bar")) {
+		t.Fatalf("unexpected key: %v", k)
+	}
+	if k, _ := c.Next(); !bytes.Equal(k, []byte("foo")) {
+		t.Fatalf("unexpected key: %v", k)
+	}
+
+	if err := tx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a cursor can skip over empty pages that have been deleted.
+func TestCursor_First_EmptyPages(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Create 1000 keys in the "widgets" bucket.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		for i := 0; i < 1000; i++ {
+			if err := b.Put(u64tob(uint64(i)), []byte{}); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Delete half the keys and then try to iterate.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		for i := 0; i < 600; i++ {
+			if err := b.Delete(u64tob(uint64(i))); err != nil {
+				t.Fatal(err)
+			}
+		}
+
+		c := b.Cursor()
+		var n int
+		for k, _ := c.First(); k != nil; k, _ = c.Next() {
+			n++
+		}
+		if n != 400 {
+			t.Fatalf("unexpected key count: %d", n)
+		}
+
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx can iterate over all elements in a bucket.
+func TestCursor_QuickCheck(t *testing.T) {
+	f := func(items testdata) bool {
+		db := MustOpenDB()
+		defer db.MustClose()
+
+		// Bulk insert all values.
+		tx, err := db.Begin(true)
+		if err != nil {
+			t.Fatal(err)
+		}
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for _, item := range items {
+			if err := b.Put(item.Key, item.Value); err != nil {
+				t.Fatal(err)
+			}
+		}
+		if err := tx.Commit(); err != nil {
+			t.Fatal(err)
+		}
+
+		// Sort test data.
+		sort.Sort(items)
+
+		// Iterate over all items and check consistency.
+		var index = 0
+		tx, err = db.Begin(false)
+		if err != nil {
+			t.Fatal(err)
+		}
+
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		for k, v := c.First(); k != nil && index < len(items); k, v = c.Next() {
+			if !bytes.Equal(k, items[index].Key) {
+				t.Fatalf("unexpected key: %v", k)
+			} else if !bytes.Equal(v, items[index].Value) {
+				t.Fatalf("unexpected value: %v", v)
+			}
+			index++
+		}
+		if len(items) != index {
+			t.Fatalf("unexpected item count: %v, expected %v", len(items), index)
+		}
+
+		if err := tx.Rollback(); err != nil {
+			t.Fatal(err)
+		}
+
+		return true
+	}
+	if err := quick.Check(f, qconfig()); err != nil {
+		t.Error(err)
+	}
+}
+
+// Ensure that a transaction can iterate over all elements in a bucket in reverse.
+func TestCursor_QuickCheck_Reverse(t *testing.T) {
+	f := func(items testdata) bool {
+		db := MustOpenDB()
+		defer db.MustClose()
+
+		// Bulk insert all values.
+		tx, err := db.Begin(true)
+		if err != nil {
+			t.Fatal(err)
+		}
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		for _, item := range items {
+			if err := b.Put(item.Key, item.Value); err != nil {
+				t.Fatal(err)
+			}
+		}
+		if err := tx.Commit(); err != nil {
+			t.Fatal(err)
+		}
+
+		// Sort test data.
+		sort.Sort(revtestdata(items))
+
+		// Iterate over all items and check consistency.
+		var index = 0
+		tx, err = db.Begin(false)
+		if err != nil {
+			t.Fatal(err)
+		}
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		for k, v := c.Last(); k != nil && index < len(items); k, v = c.Prev() {
+			if !bytes.Equal(k, items[index].Key) {
+				t.Fatalf("unexpected key: %v", k)
+			} else if !bytes.Equal(v, items[index].Value) {
+				t.Fatalf("unexpected value: %v", v)
+			}
+			index++
+		}
+		if len(items) != index {
+			t.Fatalf("unexpected item count: %v, expected %v", len(items), index)
+		}
+
+		if err := tx.Rollback(); err != nil {
+			t.Fatal(err)
+		}
+
+		return true
+	}
+	if err := quick.Check(f, qconfig()); err != nil {
+		t.Error(err)
+	}
+}
+
+// Ensure that a Tx cursor can iterate over subbuckets.
+func TestCursor_QuickCheck_BucketsOnly(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("baz")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		var names []string
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		for k, v := c.First(); k != nil; k, v = c.Next() {
+			names = append(names, string(k))
+			if v != nil {
+				t.Fatalf("unexpected value: %v", v)
+			}
+		}
+		if !reflect.DeepEqual(names, []string{"bar", "baz", "foo"}) {
+			t.Fatalf("unexpected names: %+v", names)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that a Tx cursor can reverse iterate over subbuckets.
+func TestCursor_QuickCheck_BucketsOnly_Reverse(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if _, err := b.CreateBucket([]byte("baz")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		var names []string
+		c := tx.Bucket([]byte("widgets")).Cursor()
+		for k, v := c.Last(); k != nil; k, v = c.Prev() {
+			names = append(names, string(k))
+			if v != nil {
+				t.Fatalf("unexpected value: %v", v)
+			}
+		}
+		if !reflect.DeepEqual(names, []string{"foo", "baz", "bar"}) {
+			t.Fatalf("unexpected names: %+v", names)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func ExampleCursor() {
+	// Open the database.
+	db, err := bolt.Open(tempfile(), 0666, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer os.Remove(db.Path())
+
+	// Start a read-write transaction.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create a new bucket.
+		b, err := tx.CreateBucket([]byte("animals"))
+		if err != nil {
+			return err
+		}
+
+		// Insert data into a bucket.
+		if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
+			log.Fatal(err)
+		}
+		if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
+			log.Fatal(err)
+		}
+		if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
+			log.Fatal(err)
+		}
+
+		// Create a cursor for iteration.
+		c := b.Cursor()
+
+		// Iterate over items in sorted key order. This starts from the
+		// first key/value pair and updates the k/v variables to the
+		// next key/value on each iteration.
+		//
+		// The loop finishes at the end of the cursor when a nil key is returned.
+		for k, v := c.First(); k != nil; k, v = c.Next() {
+			fmt.Printf("A %s is %s.\n", k, v)
+		}
+
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	if err := db.Close(); err != nil {
+		log.Fatal(err)
+	}
+
+	// Output:
+	// A cat is lame.
+	// A dog is fun.
+	// A liger is awesome.
+}
+
+func ExampleCursor_reverse() {
+	// Open the database.
+	db, err := bolt.Open(tempfile(), 0666, nil)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer os.Remove(db.Path())
+
+	// Start a read-write transaction.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		// Create a new bucket.
+		b, err := tx.CreateBucket([]byte("animals"))
+		if err != nil {
+			return err
+		}
+
+		// Insert data into a bucket.
+		if err := b.Put([]byte("dog"), []byte("fun")); err != nil {
+			log.Fatal(err)
+		}
+		if err := b.Put([]byte("cat"), []byte("lame")); err != nil {
+			log.Fatal(err)
+		}
+		if err := b.Put([]byte("liger"), []byte("awesome")); err != nil {
+			log.Fatal(err)
+		}
+
+		// Create a cursor for iteration.
+		c := b.Cursor()
+
+		// Iterate over items in reverse sorted key order. This starts
+		// from the last key/value pair and updates the k/v variables to
+		// the previous key/value on each iteration.
+		//
+		// The loop finishes at the beginning of the cursor when a nil key
+		// is returned.
+		for k, v := c.Last(); k != nil; k, v = c.Prev() {
+			fmt.Printf("A %s is %s.\n", k, v)
+		}
+
+		return nil
+	}); err != nil {
+		log.Fatal(err)
+	}
+
+	// Close the database to release the file lock.
+	if err := db.Close(); err != nil {
+		log.Fatal(err)
+	}
+
+	// Output:
+	// A liger is awesome.
+	// A dog is fun.
+	// A cat is lame.
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/db.go b/grove/vendor/github.com/coreos/bbolt/db.go
new file mode 100644
index 000000000..d5c53f4a2
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/db.go
@@ -0,0 +1,1136 @@
+package bolt
+
+import (
+	"errors"
+	"fmt"
+	"hash/fnv"
+	"log"
+	"os"
+	"runtime"
+	"sort"
+	"sync"
+	"time"
+	"unsafe"
+)
+
+// The largest step that can be taken when remapping the mmap.
+const maxMmapStep = 1 << 30 // 1GB
+
+// The data file format version.
+const version = 2
+
+// Represents a marker value to indicate that a file is a Bolt DB.
+const magic uint32 = 0xED0CDAED
+
+const pgidNoFreelist pgid = 0xffffffffffffffff
+
+// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when
+// syncing changes to a file.  This is required as some operating systems,
+// such as OpenBSD, do not have a unified buffer cache (UBC) and writes
+// must be synchronized using the msync(2) syscall.
+const IgnoreNoSync = runtime.GOOS == "openbsd"
+
+// Default values if not set in a DB instance.
+const (
+	DefaultMaxBatchSize  int = 1000
+	DefaultMaxBatchDelay     = 10 * time.Millisecond
+	DefaultAllocSize         = 16 * 1024 * 1024
+)
+
+// default page size for db is set to the OS page size.
+var defaultPageSize = os.Getpagesize()
+
+// The time elapsed between consecutive file locking attempts.
+const flockRetryTimeout = 50 * time.Millisecond
+
+// DB represents a collection of buckets persisted to a file on disk.
+// All data access is performed through transactions which can be obtained through the DB.
+// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
+type DB struct {
+	// When enabled, the database will perform a Check() after every commit.
+	// A panic is issued if the database is in an inconsistent state. This
+	// flag has a large performance impact so it should only be used for
+	// debugging purposes.
+	StrictMode bool
+
+	// Setting the NoSync flag will cause the database to skip fsync()
+	// calls after each commit. This can be useful when bulk loading data
+	// into a database and you can restart the bulk load in the event of
+	// a system failure or database corruption. Do not set this flag for
+	// normal use.
+	//
+	// If the package global IgnoreNoSync constant is true, this value is
+	// ignored.  See the comment on that constant for more details.
+	//
+	// THIS IS UNSAFE. PLEASE USE WITH CAUTION.
+	NoSync bool
+
+	// When true, skips syncing freelist to disk. This improves the database
+	// write performance under normal operation, but requires a full database
+	// re-sync during recovery.
+	NoFreelistSync bool
+
+	// When true, skips the truncate call when growing the database.
+	// Setting this to true is only safe on non-ext3/ext4 systems.
+	// Skipping truncation avoids preallocation of hard drive space and
+	// bypasses a truncate() and fsync() syscall on remapping.
+	//
+	// https://github.com/boltdb/bolt/issues/284
+	NoGrowSync bool
+
+	// If you want to read the entire database fast, you can set MmapFlag to
+	// syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
+	MmapFlags int
+
+	// MaxBatchSize is the maximum size of a batch. Default value is
+	// copied from DefaultMaxBatchSize in Open.
+	//
+	// If <=0, disables batching.
+	//
+	// Do not change concurrently with calls to Batch.
+	MaxBatchSize int
+
+	// MaxBatchDelay is the maximum delay before a batch starts.
+	// Default value is copied from DefaultMaxBatchDelay in Open.
+	//
+	// If <=0, effectively disables batching.
+	//
+	// Do not change concurrently with calls to Batch.
+	MaxBatchDelay time.Duration
+
+	// AllocSize is the amount of space allocated when the database
+	// needs to create new pages. This is done to amortize the cost
+	// of truncate() and fsync() when growing the data file.
+	AllocSize int
+
+	path     string
+	file     *os.File
+	lockfile *os.File // windows only
+	dataref  []byte   // mmap'ed readonly, write throws SEGV
+	data     *[maxMapSize]byte
+	datasz   int
+	filesz   int // current on disk file size
+	meta0    *meta
+	meta1    *meta
+	pageSize int
+	opened   bool
+	rwtx     *Tx
+	txs      []*Tx
+	stats    Stats
+
+	freelist     *freelist
+	freelistLoad sync.Once
+
+	pagePool sync.Pool
+
+	batchMu sync.Mutex
+	batch   *batch
+
+	rwlock   sync.Mutex   // Allows only one writer at a time.
+	metalock sync.Mutex   // Protects meta page access.
+	mmaplock sync.RWMutex // Protects mmap access during remapping.
+	statlock sync.RWMutex // Protects stats access.
+
+	ops struct {
+		writeAt func(b []byte, off int64) (n int, err error)
+	}
+
+	// Read only mode.
+	// When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
+	readOnly bool
+}
+
+// Path returns the path to currently open database file.
+func (db *DB) Path() string {
+	return db.path
+}
+
+// GoString returns the Go string representation of the database.
+func (db *DB) GoString() string {
+	return fmt.Sprintf("bolt.DB{path:%q}", db.path)
+}
+
+// String returns the string representation of the database.
+func (db *DB) String() string {
+	return fmt.Sprintf("DB<%q>", db.path)
+}
+
+// Open creates and opens a database at the given path.
+// If the file does not exist then it will be created automatically.
+// Passing in nil options will cause Bolt to open the database with the default options.
+func Open(path string, mode os.FileMode, options *Options) (*DB, error) {
+	db := &DB{
+		opened: true,
+	}
+	// Set default options if no options are provided.
+	if options == nil {
+		options = DefaultOptions
+	}
+	db.NoSync = options.NoSync
+	db.NoGrowSync = options.NoGrowSync
+	db.MmapFlags = options.MmapFlags
+	db.NoFreelistSync = options.NoFreelistSync
+
+	// Set default values for later DB operations.
+	db.MaxBatchSize = DefaultMaxBatchSize
+	db.MaxBatchDelay = DefaultMaxBatchDelay
+	db.AllocSize = DefaultAllocSize
+
+	flag := os.O_RDWR
+	if options.ReadOnly {
+		flag = os.O_RDONLY
+		db.readOnly = true
+	}
+
+	// Open data file and separate sync handler for metadata writes.
+	db.path = path
+	var err error
+	if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil {
+		_ = db.close()
+		return nil, err
+	}
+
+	// Lock file so that other processes using Bolt in read-write mode cannot
+	// use the database  at the same time. This would cause corruption since
+	// the two processes would write meta pages and free pages separately.
+	// The database file is locked exclusively (only one process can grab the lock)
+	// if !options.ReadOnly.
+	// The database file is locked using the shared lock (more than one process may
+	// hold a lock at the same time) otherwise (options.ReadOnly is set).
+	if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil {
+		db.lockfile = nil // make 'unused' happy. TODO: rework locks
+		_ = db.close()
+		return nil, err
+	}
+
+	// Default values for test hooks
+	db.ops.writeAt = db.file.WriteAt
+
+	if db.pageSize = options.PageSize; db.pageSize == 0 {
+		// Set the default page size to the OS page size.
+		db.pageSize = defaultPageSize
+	}
+
+	// Initialize the database if it doesn't exist.
+	if info, err := db.file.Stat(); err != nil {
+		return nil, err
+	} else if info.Size() == 0 {
+		// Initialize new files with meta pages.
+		if err := db.init(); err != nil {
+			return nil, err
+		}
+	} else {
+		// Read the first meta page to determine the page size.
+		var buf [0x1000]byte
+		// If we can't read the page size, but can read a page, assume
+		// it's the same as the OS or one given -- since that's how the
+		// page size was chosen in the first place.
+		//
+		// If the first page is invalid and this OS uses a different
+		// page size than what the database was created with then we
+		// are out of luck and cannot access the database.
+		//
+		// TODO: scan for next page
+		if bw, err := db.file.ReadAt(buf[:], 0); err == nil && bw == len(buf) {
+			if m := db.pageInBuffer(buf[:], 0).meta(); m.validate() == nil {
+				db.pageSize = int(m.pageSize)
+			}
+		} else {
+			return nil, ErrInvalid
+		}
+	}
+
+	// Initialize page pool.
+	db.pagePool = sync.Pool{
+		New: func() interface{} {
+			return make([]byte, db.pageSize)
+		},
+	}
+
+	// Memory map the data file.
+	if err := db.mmap(options.InitialMmapSize); err != nil {
+		_ = db.close()
+		return nil, err
+	}
+
+	if db.readOnly {
+		return db, nil
+	}
+
+	db.loadFreelist()
+
+	// Flush freelist when transitioning from no sync to sync so
+	// NoFreelistSync unaware boltdb can open the db later.
+	if !db.NoFreelistSync && !db.hasSyncedFreelist() {
+		tx, err := db.Begin(true)
+		if tx != nil {
+			err = tx.Commit()
+		}
+		if err != nil {
+			_ = db.close()
+			return nil, err
+		}
+	}
+
+	// Mark the database as opened and return.
+	return db, nil
+}
+
+// loadFreelist reads the freelist if it is synced, or reconstructs it
+// by scanning the DB if it is not synced. It assumes there are no
+// concurrent accesses being made to the freelist.
+func (db *DB) loadFreelist() {
+	db.freelistLoad.Do(func() {
+		db.freelist = newFreelist()
+		if !db.hasSyncedFreelist() {
+			// Reconstruct free list by scanning the DB.
+			db.freelist.readIDs(db.freepages())
+		} else {
+			// Read free list from freelist page.
+			db.freelist.read(db.page(db.meta().freelist))
+		}
+		db.stats.FreePageN = len(db.freelist.ids)
+	})
+}
+
+func (db *DB) hasSyncedFreelist() bool {
+	return db.meta().freelist != pgidNoFreelist
+}
+
+// mmap opens the underlying memory-mapped file and initializes the meta references.
+// minsz is the minimum size that the new mmap can be.
+func (db *DB) mmap(minsz int) error {
+	db.mmaplock.Lock()
+	defer db.mmaplock.Unlock()
+
+	info, err := db.file.Stat()
+	if err != nil {
+		return fmt.Errorf("mmap stat error: %s", err)
+	} else if int(info.Size()) < db.pageSize*2 {
+		return fmt.Errorf("file size too small")
+	}
+
+	// Ensure the size is at least the minimum size.
+	var size = int(info.Size())
+	if size < minsz {
+		size = minsz
+	}
+	size, err = db.mmapSize(size)
+	if err != nil {
+		return err
+	}
+
+	// Dereference all mmap references before unmapping.
+	if db.rwtx != nil {
+		db.rwtx.root.dereference()
+	}
+
+	// Unmap existing data before continuing.
+	if err := db.munmap(); err != nil {
+		return err
+	}
+
+	// Memory-map the data file as a byte slice.
+	if err := mmap(db, size); err != nil {
+		return err
+	}
+
+	// Save references to the meta pages.
+	db.meta0 = db.page(0).meta()
+	db.meta1 = db.page(1).meta()
+
+	// Validate the meta pages. We only return an error if both meta pages fail
+	// validation, since meta0 failing validation means that it wasn't saved
+	// properly -- but we can recover using meta1. And vice-versa.
+	err0 := db.meta0.validate()
+	err1 := db.meta1.validate()
+	if err0 != nil && err1 != nil {
+		return err0
+	}
+
+	return nil
+}
+
+// munmap unmaps the data file from memory.
+func (db *DB) munmap() error {
+	if err := munmap(db); err != nil {
+		return fmt.Errorf("unmap error: " + err.Error())
+	}
+	return nil
+}
+
+// mmapSize determines the appropriate size for the mmap given the current size
+// of the database. The minimum size is 32KB and doubles until it reaches 1GB.
+// Returns an error if the new mmap size is greater than the max allowed.
+func (db *DB) mmapSize(size int) (int, error) {
+	// Double the size from 32KB until 1GB.
+	for i := uint(15); i <= 30; i++ {
+		if size <= 1<<i {
+			return 1 << i, nil
+		}
+	}
+
+	// Verify the requested size is not above the maximum allowed.
+	if size > maxMapSize {
+		return 0, fmt.Errorf("mmap too large")
+	}
+
+	// If larger than 1GB then grow by 1GB at a time.
+	sz := int64(size)
+	if remainder := sz % int64(maxMmapStep); remainder > 0 {
+		sz += int64(maxMmapStep) - remainder
+	}
+
+	// Ensure that the mmap size is a multiple of the page size.
+	// This should always be true since we're incrementing in MBs.
+	pageSize := int64(db.pageSize)
+	if (sz % pageSize) != 0 {
+		sz = ((sz / pageSize) + 1) * pageSize
+	}
+
+	// If we've exceeded the max size then only grow up to the max size.
+	if sz > maxMapSize {
+		sz = maxMapSize
+	}
+
+	return int(sz), nil
+}
+
+// init creates a new database file and initializes its meta pages.
+func (db *DB) init() error {
+	// Create two meta pages on a buffer.
+	buf := make([]byte, db.pageSize*4)
+	for i := 0; i < 2; i++ {
+		p := db.pageInBuffer(buf[:], pgid(i))
+		p.id = pgid(i)
+		p.flags = metaPageFlag
+
+		// Initialize the meta page.
+		m := p.meta()
+		m.magic = magic
+		m.version = version
+		m.pageSize = uint32(db.pageSize)
+		m.freelist = 2
+		m.root = bucket{root: 3}
+		m.pgid = 4
+		m.txid = txid(i)
+		m.checksum = m.sum64()
+	}
+
+	// Write an empty freelist at page 3.
+	p := db.pageInBuffer(buf[:], pgid(2))
+	p.id = pgid(2)
+	p.flags = freelistPageFlag
+	p.count = 0
+
+	// Write an empty leaf page at page 4.
+	p = db.pageInBuffer(buf[:], pgid(3))
+	p.id = pgid(3)
+	p.flags = leafPageFlag
+	p.count = 0
+
+	// Write the buffer to our data file.
+	if _, err := db.ops.writeAt(buf, 0); err != nil {
+		return err
+	}
+	if err := fdatasync(db); err != nil {
+		return err
+	}
+
+	return nil
+}
+
+// Close releases all database resources.
+// It will block waiting for any open transactions to finish
+// before closing the database and returning.
+func (db *DB) Close() error {
+	db.rwlock.Lock()
+	defer db.rwlock.Unlock()
+
+	db.metalock.Lock()
+	defer db.metalock.Unlock()
+
+	db.mmaplock.RLock()
+	defer db.mmaplock.RUnlock()
+
+	return db.close()
+}
+
+func (db *DB) close() error {
+	if !db.opened {
+		return nil
+	}
+
+	db.opened = false
+
+	db.freelist = nil
+
+	// Clear ops.
+	db.ops.writeAt = nil
+
+	// Close the mmap.
+	if err := db.munmap(); err != nil {
+		return err
+	}
+
+	// Close file handles.
+	if db.file != nil {
+		// No need to unlock read-only file.
+		if !db.readOnly {
+			// Unlock the file.
+			if err := funlock(db); err != nil {
+				log.Printf("bolt.Close(): funlock error: %s", err)
+			}
+		}
+
+		// Close the file descriptor.
+		if err := db.file.Close(); err != nil {
+			return fmt.Errorf("db file close: %s", err)
+		}
+		db.file = nil
+	}
+
+	db.path = ""
+	return nil
+}
+
+// Begin starts a new transaction.
+// Multiple read-only transactions can be used concurrently but only one
+// write transaction can be used at a time. Starting multiple write transactions
+// will cause the calls to block and be serialized until the current write
+// transaction finishes.
+//
+// Transactions should not be dependent on one another. Opening a read
+// transaction and a write transaction in the same goroutine can cause the
+// writer to deadlock because the database periodically needs to re-mmap itself
+// as it grows and it cannot do that while a read transaction is open.
+//
+// If a long running read transaction (for example, a snapshot transaction) is
+// needed, you might want to set DB.InitialMmapSize to a large enough value
+// to avoid potential blocking of write transaction.
+//
+// IMPORTANT: You must close read-only transactions after you are finished or
+// else the database will not reclaim old pages.
+func (db *DB) Begin(writable bool) (*Tx, error) {
+	if writable {
+		return db.beginRWTx()
+	}
+	return db.beginTx()
+}
+
+func (db *DB) beginTx() (*Tx, error) {
+	// Lock the meta pages while we initialize the transaction. We obtain
+	// the meta lock before the mmap lock because that's the order that the
+	// write transaction will obtain them.
+	db.metalock.Lock()
+
+	// Obtain a read-only lock on the mmap. When the mmap is remapped it will
+	// obtain a write lock so all transactions must finish before it can be
+	// remapped.
+	db.mmaplock.RLock()
+
+	// Exit if the database is not open yet.
+	if !db.opened {
+		db.mmaplock.RUnlock()
+		db.metalock.Unlock()
+		return nil, ErrDatabaseNotOpen
+	}
+
+	// Create a transaction associated with the database.
+	t := &Tx{}
+	t.init(db)
+
+	// Keep track of transaction until it closes.
+	db.txs = append(db.txs, t)
+	n := len(db.txs)
+
+	// Unlock the meta pages.
+	db.metalock.Unlock()
+
+	// Update the transaction stats.
+	db.statlock.Lock()
+	db.stats.TxN++
+	db.stats.OpenTxN = n
+	db.statlock.Unlock()
+
+	return t, nil
+}
+
+func (db *DB) beginRWTx() (*Tx, error) {
+	// If the database was opened with Options.ReadOnly, return an error.
+	if db.readOnly {
+		return nil, ErrDatabaseReadOnly
+	}
+
+	// Obtain writer lock. This is released by the transaction when it closes.
+	// This enforces only one writer transaction at a time.
+	db.rwlock.Lock()
+
+	// Once we have the writer lock then we can lock the meta pages so that
+	// we can set up the transaction.
+	db.metalock.Lock()
+	defer db.metalock.Unlock()
+
+	// Exit if the database is not open yet.
+	if !db.opened {
+		db.rwlock.Unlock()
+		return nil, ErrDatabaseNotOpen
+	}
+
+	// Create a transaction associated with the database.
+	t := &Tx{writable: true}
+	t.init(db)
+	db.rwtx = t
+	db.freePages()
+	return t, nil
+}
+
+// freePages releases any pages associated with closed read-only transactions.
+func (db *DB) freePages() {
+	// Free all pending pages prior to earliest open transaction.
+	sort.Sort(txsById(db.txs))
+	minid := txid(0xFFFFFFFFFFFFFFFF)
+	if len(db.txs) > 0 {
+		minid = db.txs[0].meta.txid
+	}
+	if minid > 0 {
+		db.freelist.release(minid - 1)
+	}
+	// Release unused txid extents.
+	for _, t := range db.txs {
+		db.freelist.releaseRange(minid, t.meta.txid-1)
+		minid = t.meta.txid + 1
+	}
+	db.freelist.releaseRange(minid, txid(0xFFFFFFFFFFFFFFFF))
+	// Any page both allocated and freed in an extent is safe to release.
+}
+
+type txsById []*Tx
+
+func (t txsById) Len() int           { return len(t) }
+func (t txsById) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
+func (t txsById) Less(i, j int) bool { return t[i].meta.txid < t[j].meta.txid }
+
+// removeTx removes a transaction from the database.
+func (db *DB) removeTx(tx *Tx) {
+	// Release the read lock on the mmap.
+	db.mmaplock.RUnlock()
+
+	// Use the meta lock to restrict access to the DB object.
+	db.metalock.Lock()
+
+	// Remove the transaction.
+	for i, t := range db.txs {
+		if t == tx {
+			last := len(db.txs) - 1
+			db.txs[i] = db.txs[last]
+			db.txs[last] = nil
+			db.txs = db.txs[:last]
+			break
+		}
+	}
+	n := len(db.txs)
+
+	// Unlock the meta pages.
+	db.metalock.Unlock()
+
+	// Merge statistics.
+	db.statlock.Lock()
+	db.stats.OpenTxN = n
+	db.stats.TxStats.add(&tx.stats)
+	db.statlock.Unlock()
+}
+
+// Update executes a function within the context of a read-write managed transaction.
+// If no error is returned from the function then the transaction is committed.
+// If an error is returned then the entire transaction is rolled back.
+// Any error that is returned from the function or returned from the commit is
+// returned from the Update() method.
+//
+// Attempting to manually commit or rollback within the function will cause a panic.
+func (db *DB) Update(fn func(*Tx) error) error {
+	t, err := db.Begin(true)
+	if err != nil {
+		return err
+	}
+
+	// Make sure the transaction rolls back in the event of a panic.
+	defer func() {
+		if t.db != nil {
+			t.rollback()
+		}
+	}()
+
+	// Mark as a managed tx so that the inner function cannot manually commit.
+	t.managed = true
+
+	// If an error is returned from the function then rollback and return error.
+	err = fn(t)
+	t.managed = false
+	if err != nil {
+		_ = t.Rollback()
+		return err
+	}
+
+	return t.Commit()
+}
+
+// View executes a function within the context of a managed read-only transaction.
+// Any error that is returned from the function is returned from the View() method.
+//
+// Attempting to manually rollback within the function will cause a panic.
+func (db *DB) View(fn func(*Tx) error) error {
+	t, err := db.Begin(false)
+	if err != nil {
+		return err
+	}
+
+	// Make sure the transaction rolls back in the event of a panic.
+	defer func() {
+		if t.db != nil {
+			t.rollback()
+		}
+	}()
+
+	// Mark as a managed tx so that the inner function cannot manually rollback.
+	t.managed = true
+
+	// If an error is returned from the function then pass it through.
+	err = fn(t)
+	t.managed = false
+	if err != nil {
+		_ = t.Rollback()
+		return err
+	}
+
+	return t.Rollback()
+}
+
+// Batch calls fn as part of a batch. It behaves similar to Update,
+// except:
+//
+// 1. concurrent Batch calls can be combined into a single Bolt
+// transaction.
+//
+// 2. the function passed to Batch may be called multiple times,
+// regardless of whether it returns error or not.
+//
+// This means that Batch function side effects must be idempotent and
+// take permanent effect only after a successful return is seen in
+// caller.
+//
+// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
+// and DB.MaxBatchDelay, respectively.
+//
+// Batch is only useful when there are multiple goroutines calling it.
+func (db *DB) Batch(fn func(*Tx) error) error {
+	errCh := make(chan error, 1)
+
+	db.batchMu.Lock()
+	if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) {
+		// There is no existing batch, or the existing batch is full; start a new one.
+		db.batch = &batch{
+			db: db,
+		}
+		db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger)
+	}
+	db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh})
+	if len(db.batch.calls) >= db.MaxBatchSize {
+		// wake up batch, it's ready to run
+		go db.batch.trigger()
+	}
+	db.batchMu.Unlock()
+
+	err := <-errCh
+	if err == trySolo {
+		err = db.Update(fn)
+	}
+	return err
+}
+
+type call struct {
+	fn  func(*Tx) error
+	err chan<- error
+}
+
+type batch struct {
+	db    *DB
+	timer *time.Timer
+	start sync.Once
+	calls []call
+}
+
+// trigger runs the batch if it hasn't already been run.
+func (b *batch) trigger() {
+	b.start.Do(b.run)
+}
+
+// run performs the transactions in the batch and communicates results
+// back to DB.Batch.
+func (b *batch) run() {
+	b.db.batchMu.Lock()
+	b.timer.Stop()
+	// Make sure no new work is added to this batch, but don't break
+	// other batches.
+	if b.db.batch == b {
+		b.db.batch = nil
+	}
+	b.db.batchMu.Unlock()
+
+retry:
+	for len(b.calls) > 0 {
+		var failIdx = -1
+		err := b.db.Update(func(tx *Tx) error {
+			for i, c := range b.calls {
+				if err := safelyCall(c.fn, tx); err != nil {
+					failIdx = i
+					return err
+				}
+			}
+			return nil
+		})
+
+		if failIdx >= 0 {
+			// take the failing transaction out of the batch. it's
+			// safe to shorten b.calls here because db.batch no longer
+			// points to us, and we hold the mutex anyway.
+			c := b.calls[failIdx]
+			b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1]
+			// tell the submitter re-run it solo, continue with the rest of the batch
+			c.err <- trySolo
+			continue retry
+		}
+
+		// pass success, or bolt internal errors, to all callers
+		for _, c := range b.calls {
+			c.err <- err
+		}
+		break retry
+	}
+}
+
+// trySolo is a special sentinel error value used for signaling that a
+// transaction function should be re-run. It should never be seen by
+// callers.
+var trySolo = errors.New("batch function returned an error and should be re-run solo")
+
+type panicked struct {
+	reason interface{}
+}
+
+func (p panicked) Error() string {
+	if err, ok := p.reason.(error); ok {
+		return err.Error()
+	}
+	return fmt.Sprintf("panic: %v", p.reason)
+}
+
+func safelyCall(fn func(*Tx) error, tx *Tx) (err error) {
+	defer func() {
+		if p := recover(); p != nil {
+			err = panicked{p}
+		}
+	}()
+	return fn(tx)
+}
+
+// Sync executes fdatasync() against the database file handle.
+//
+// This is not necessary under normal operation, however, if you use NoSync
+// then it allows you to force the database file to sync against the disk.
+func (db *DB) Sync() error { return fdatasync(db) }
+
+// Stats retrieves ongoing performance stats for the database.
+// This is only updated when a transaction closes.
+func (db *DB) Stats() Stats {
+	db.statlock.RLock()
+	defer db.statlock.RUnlock()
+	return db.stats
+}
+
+// This is for internal access to the raw data bytes from the C cursor, use
+// carefully, or not at all.
+func (db *DB) Info() *Info {
+	return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize}
+}
+
+// page retrieves a page reference from the mmap based on the current page size.
+func (db *DB) page(id pgid) *page {
+	pos := id * pgid(db.pageSize)
+	return (*page)(unsafe.Pointer(&db.data[pos]))
+}
+
+// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
+func (db *DB) pageInBuffer(b []byte, id pgid) *page {
+	return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)]))
+}
+
+// meta retrieves the current meta page reference.
+func (db *DB) meta() *meta {
+	// We have to return the meta with the highest txid which doesn't fail
+	// validation. Otherwise, we can cause errors when in fact the database is
+	// in a consistent state. metaA is the one with the higher txid.
+	metaA := db.meta0
+	metaB := db.meta1
+	if db.meta1.txid > db.meta0.txid {
+		metaA = db.meta1
+		metaB = db.meta0
+	}
+
+	// Use higher meta page if valid. Otherwise fallback to previous, if valid.
+	if err := metaA.validate(); err == nil {
+		return metaA
+	} else if err := metaB.validate(); err == nil {
+		return metaB
+	}
+
+	// This should never be reached, because both meta1 and meta0 were validated
+	// on mmap() and we do fsync() on every write.
+	panic("bolt.DB.meta(): invalid meta pages")
+}
+
+// allocate returns a contiguous block of memory starting at a given page.
+func (db *DB) allocate(txid txid, count int) (*page, error) {
+	// Allocate a temporary buffer for the page.
+	var buf []byte
+	if count == 1 {
+		buf = db.pagePool.Get().([]byte)
+	} else {
+		buf = make([]byte, count*db.pageSize)
+	}
+	p := (*page)(unsafe.Pointer(&buf[0]))
+	p.overflow = uint32(count - 1)
+
+	// Use pages from the freelist if they are available.
+	if p.id = db.freelist.allocate(txid, count); p.id != 0 {
+		return p, nil
+	}
+
+	// Resize mmap() if we're at the end.
+	p.id = db.rwtx.meta.pgid
+	var minsz = int((p.id+pgid(count))+1) * db.pageSize
+	if minsz >= db.datasz {
+		if err := db.mmap(minsz); err != nil {
+			return nil, fmt.Errorf("mmap allocate error: %s", err)
+		}
+	}
+
+	// Move the page id high water mark.
+	db.rwtx.meta.pgid += pgid(count)
+
+	return p, nil
+}
+
+// grow grows the size of the database to the given sz.
+func (db *DB) grow(sz int) error {
+	// Ignore if the new size is less than available file size.
+	if sz <= db.filesz {
+		return nil
+	}
+
+	// If the data is smaller than the alloc size then only allocate what's needed.
+	// Once it goes over the allocation size then allocate in chunks.
+	if db.datasz < db.AllocSize {
+		sz = db.datasz
+	} else {
+		sz += db.AllocSize
+	}
+
+	// Truncate and fsync to ensure file size metadata is flushed.
+	// https://github.com/boltdb/bolt/issues/284
+	if !db.NoGrowSync && !db.readOnly {
+		if runtime.GOOS != "windows" {
+			if err := db.file.Truncate(int64(sz)); err != nil {
+				return fmt.Errorf("file resize error: %s", err)
+			}
+		}
+		if err := db.file.Sync(); err != nil {
+			return fmt.Errorf("file sync error: %s", err)
+		}
+	}
+
+	db.filesz = sz
+	return nil
+}
+
+func (db *DB) IsReadOnly() bool {
+	return db.readOnly
+}
+
+func (db *DB) freepages() []pgid {
+	tx, err := db.beginTx()
+	defer func() {
+		err = tx.Rollback()
+		if err != nil {
+			panic("freepages: failed to rollback tx")
+		}
+	}()
+	if err != nil {
+		panic("freepages: failed to open read only tx")
+	}
+
+	reachable := make(map[pgid]*page)
+	nofreed := make(map[pgid]bool)
+	ech := make(chan error)
+	go func() {
+		for e := range ech {
+			panic(fmt.Sprintf("freepages: failed to get all reachable pages (%v)", e))
+		}
+	}()
+	tx.checkBucket(&tx.root, reachable, nofreed, ech)
+	close(ech)
+
+	var fids []pgid
+	for i := pgid(2); i < db.meta().pgid; i++ {
+		if _, ok := reachable[i]; !ok {
+			fids = append(fids, i)
+		}
+	}
+	return fids
+}
+
+// Options represents the options that can be set when opening a database.
+type Options struct {
+	// Timeout is the amount of time to wait to obtain a file lock.
+	// When set to zero it will wait indefinitely. This option is only
+	// available on Darwin and Linux.
+	Timeout time.Duration
+
+	// Sets the DB.NoGrowSync flag before memory mapping the file.
+	NoGrowSync bool
+
+	// Do not sync freelist to disk. This improves the database write performance
+	// under normal operation, but requires a full database re-sync during recovery.
+	NoFreelistSync bool
+
+	// Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
+	// grab a shared lock (UNIX).
+	ReadOnly bool
+
+	// Sets the DB.MmapFlags flag before memory mapping the file.
+	MmapFlags int
+
+	// InitialMmapSize is the initial mmap size of the database
+	// in bytes. Read transactions won't block write transaction
+	// if the InitialMmapSize is large enough to hold database mmap
+	// size. (See DB.Begin for more information)
+	//
+	// If <=0, the initial map size is 0.
+	// If initialMmapSize is smaller than the previous database size,
+	// it takes no effect.
+	InitialMmapSize int
+
+	// PageSize overrides the default OS page size.
+	PageSize int
+
+	// NoSync sets the initial value of DB.NoSync. Normally this can just be
+	// set directly on the DB itself when returned from Open(), but this option
+	// is useful in APIs which expose Options but not the underlying DB.
+	NoSync bool
+}
+
+// DefaultOptions represent the options used if nil options are passed into Open().
+// No timeout is used which will cause Bolt to wait indefinitely for a lock.
+var DefaultOptions = &Options{
+	Timeout:    0,
+	NoGrowSync: false,
+}
+
+// Stats represents statistics about the database.
+type Stats struct {
+	// Freelist stats
+	FreePageN     int // total number of free pages on the freelist
+	PendingPageN  int // total number of pending pages on the freelist
+	FreeAlloc     int // total bytes allocated in free pages
+	FreelistInuse int // total bytes used by the freelist
+
+	// Transaction stats
+	TxN     int // total number of started read transactions
+	OpenTxN int // number of currently open read transactions
+
+	TxStats TxStats // global, ongoing stats.
+}
+
+// Sub calculates and returns the difference between two sets of database stats.
+// This is useful when obtaining stats at two different points and time and
+// you need the performance counters that occurred within that time span.
+func (s *Stats) Sub(other *Stats) Stats {
+	if other == nil {
+		return *s
+	}
+	var diff Stats
+	diff.FreePageN = s.FreePageN
+	diff.PendingPageN = s.PendingPageN
+	diff.FreeAlloc = s.FreeAlloc
+	diff.FreelistInuse = s.FreelistInuse
+	diff.TxN = s.TxN - other.TxN
+	diff.TxStats = s.TxStats.Sub(&other.TxStats)
+	return diff
+}
+
+type Info struct {
+	Data     uintptr
+	PageSize int
+}
+
+type meta struct {
+	magic    uint32
+	version  uint32
+	pageSize uint32
+	flags    uint32
+	root     bucket
+	freelist pgid
+	pgid     pgid
+	txid     txid
+	checksum uint64
+}
+
+// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
+func (m *meta) validate() error {
+	if m.magic != magic {
+		return ErrInvalid
+	} else if m.version != version {
+		return ErrVersionMismatch
+	} else if m.checksum != 0 && m.checksum != m.sum64() {
+		return ErrChecksum
+	}
+	return nil
+}
+
+// copy copies one meta object to another.
+func (m *meta) copy(dest *meta) {
+	*dest = *m
+}
+
+// write writes the meta onto a page.
+func (m *meta) write(p *page) {
+	if m.root.root >= m.pgid {
+		panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid))
+	} else if m.freelist >= m.pgid && m.freelist != pgidNoFreelist {
+		// TODO: reject pgidNoFreeList if !NoFreelistSync
+		panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid))
+	}
+
+	// Page id is either going to be 0 or 1 which we can determine by the transaction ID.
+	p.id = pgid(m.txid % 2)
+	p.flags |= metaPageFlag
+
+	// Calculate the checksum.
+	m.checksum = m.sum64()
+
+	m.copy(p.meta())
+}
+
+// generates the checksum for the meta.
+func (m *meta) sum64() uint64 {
+	var h = fnv.New64a()
+	_, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
+	return h.Sum64()
+}
+
+// _assert will panic with a given formatted message if the given condition is false.
+func _assert(condition bool, msg string, v ...interface{}) {
+	if !condition {
+		panic(fmt.Sprintf("assertion failed: "+msg, v...))
+	}
+}
diff --git a/grove/vendor/github.com/coreos/bbolt/db_test.go b/grove/vendor/github.com/coreos/bbolt/db_test.go
new file mode 100644
index 000000000..e3a58c3ca
--- /dev/null
+++ b/grove/vendor/github.com/coreos/bbolt/db_test.go
@@ -0,0 +1,1721 @@
+package bolt_test
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"flag"
+	"fmt"
+	"hash/fnv"
+	"io/ioutil"
+	"log"
+	"math/rand"
+	"os"
+	"path/filepath"
+	"regexp"
+	"sync"
+	"testing"
+	"time"
+	"unsafe"
+
+	"github.com/coreos/bbolt"
+)
+
+var statsFlag = flag.Bool("stats", false, "show performance stats")
+
+// pageSize is the size of one page in the data file.
+const pageSize = 4096
+
+// pageHeaderSize is the size of a page header.
+const pageHeaderSize = 16
+
+// meta represents a simplified version of a database meta page for testing.
+type meta struct {
+	magic    uint32
+	version  uint32
+	_        uint32
+	_        uint32
+	_        [16]byte
+	_        uint64
+	pgid     uint64
+	_        uint64
+	checksum uint64
+}
+
+// Ensure that a database can be opened without error.
+func TestOpen(t *testing.T) {
+	path := tempfile()
+	defer os.RemoveAll(path)
+
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	} else if db == nil {
+		t.Fatal("expected db")
+	}
+
+	if s := db.Path(); s != path {
+		t.Fatalf("unexpected path: %s", s)
+	}
+
+	if err := db.Close(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that opening a database with a blank path returns an error.
+func TestOpen_ErrPathRequired(t *testing.T) {
+	_, err := bolt.Open("", 0666, nil)
+	if err == nil {
+		t.Fatalf("expected error")
+	}
+}
+
+// Ensure that opening a database with a bad path returns an error.
+func TestOpen_ErrNotExists(t *testing.T) {
+	_, err := bolt.Open(filepath.Join(tempfile(), "bad-path"), 0666, nil)
+	if err == nil {
+		t.Fatal("expected error")
+	}
+}
+
+// Ensure that opening a file that is not a Bolt database returns ErrInvalid.
+func TestOpen_ErrInvalid(t *testing.T) {
+	path := tempfile()
+	defer os.RemoveAll(path)
+
+	f, err := os.Create(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := fmt.Fprintln(f, "this is not a bolt database"); err != nil {
+		t.Fatal(err)
+	}
+	if err := f.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrInvalid {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that opening a file with two invalid versions returns ErrVersionMismatch.
+func TestOpen_ErrVersionMismatch(t *testing.T) {
+	if pageSize != os.Getpagesize() {
+		t.Skip("page size mismatch")
+	}
+
+	// Create empty database.
+	db := MustOpenDB()
+	path := db.Path()
+	defer db.MustClose()
+
+	// Close database.
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Read data file.
+	buf, err := ioutil.ReadFile(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Rewrite meta pages.
+	meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize]))
+	meta0.version++
+	meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize]))
+	meta1.version++
+	if err := ioutil.WriteFile(path, buf, 0666); err != nil {
+		t.Fatal(err)
+	}
+
+	// Reopen data file.
+	if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrVersionMismatch {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that opening a file with two invalid checksums returns ErrChecksum.
+func TestOpen_ErrChecksum(t *testing.T) {
+	if pageSize != os.Getpagesize() {
+		t.Skip("page size mismatch")
+	}
+
+	// Create empty database.
+	db := MustOpenDB()
+	path := db.Path()
+	defer db.MustClose()
+
+	// Close database.
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Read data file.
+	buf, err := ioutil.ReadFile(path)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Rewrite meta pages.
+	meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize]))
+	meta0.pgid++
+	meta1 := (*meta)(unsafe.Pointer(&buf[pageSize+pageHeaderSize]))
+	meta1.pgid++
+	if err := ioutil.WriteFile(path, buf, 0666); err != nil {
+		t.Fatal(err)
+	}
+
+	// Reopen data file.
+	if _, err := bolt.Open(path, 0666, nil); err != bolt.ErrChecksum {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that opening a database does not increase its size.
+// https://github.com/boltdb/bolt/issues/291
+func TestOpen_Size(t *testing.T) {
+	// Open a data file.
+	db := MustOpenDB()
+	path := db.Path()
+	defer db.MustClose()
+
+	pagesize := db.Info().PageSize
+
+	// Insert until we get above the minimum 4MB size.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, _ := tx.CreateBucketIfNotExists([]byte("data"))
+		for i := 0; i < 10000; i++ {
+			if err := b.Put([]byte(fmt.Sprintf("%04d", i)), make([]byte, 1000)); err != nil {
+				t.Fatal(err)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Close database and grab the size.
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+	sz := fileSize(path)
+	if sz == 0 {
+		t.Fatalf("unexpected new file size: %d", sz)
+	}
+
+	// Reopen database, update, and check size again.
+	db0, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := db0.Update(func(tx *bolt.Tx) error {
+		if err := tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0}); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	if err := db0.Close(); err != nil {
+		t.Fatal(err)
+	}
+	newSz := fileSize(path)
+	if newSz == 0 {
+		t.Fatalf("unexpected new file size: %d", newSz)
+	}
+
+	// Compare the original size with the new size.
+	// db size might increase by a few page sizes due to the new small update.
+	if sz < newSz-5*int64(pagesize) {
+		t.Fatalf("unexpected file growth: %d => %d", sz, newSz)
+	}
+}
+
+// Ensure that opening a database beyond the max step size does not increase its size.
+// https://github.com/boltdb/bolt/issues/303
+func TestOpen_Size_Large(t *testing.T) {
+	if testing.Short() {
+		t.Skip("short mode")
+	}
+
+	// Open a data file.
+	db := MustOpenDB()
+	path := db.Path()
+	defer db.MustClose()
+
+	pagesize := db.Info().PageSize
+
+	// Insert until we get above the minimum 4MB size.
+	var index uint64
+	for i := 0; i < 10000; i++ {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			b, _ := tx.CreateBucketIfNotExists([]byte("data"))
+			for j := 0; j < 1000; j++ {
+				if err := b.Put(u64tob(index), make([]byte, 50)); err != nil {
+					t.Fatal(err)
+				}
+				index++
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	// Close database and grab the size.
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+	sz := fileSize(path)
+	if sz == 0 {
+		t.Fatalf("unexpected new file size: %d", sz)
+	} else if sz < (1 << 30) {
+		t.Fatalf("expected larger initial size: %d", sz)
+	}
+
+	// Reopen database, update, and check size again.
+	db0, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := db0.Update(func(tx *bolt.Tx) error {
+		return tx.Bucket([]byte("data")).Put([]byte{0}, []byte{0})
+	}); err != nil {
+		t.Fatal(err)
+	}
+	if err := db0.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	newSz := fileSize(path)
+	if newSz == 0 {
+		t.Fatalf("unexpected new file size: %d", newSz)
+	}
+
+	// Compare the original size with the new size.
+	// db size might increase by a few page sizes due to the new small update.
+	if sz < newSz-5*int64(pagesize) {
+		t.Fatalf("unexpected file growth: %d => %d", sz, newSz)
+	}
+}
+
+// Ensure that a re-opened database is consistent.
+func TestOpen_Check(t *testing.T) {
+	path := tempfile()
+	defer os.RemoveAll(path)
+
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err = db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil {
+		t.Fatal(err)
+	}
+	if err = db.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	db, err = bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := db.View(func(tx *bolt.Tx) error { return <-tx.Check() }); err != nil {
+		t.Fatal(err)
+	}
+	if err := db.Close(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that write errors to the meta file handler during initialization are returned.
+func TestOpen_MetaInitWriteError(t *testing.T) {
+	t.Skip("pending")
+}
+
+// Ensure that a database that is too small returns an error.
+func TestOpen_FileTooSmall(t *testing.T) {
+	path := tempfile()
+	defer os.RemoveAll(path)
+
+	db, err := bolt.Open(path, 0666, nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	pageSize := int64(db.Info().PageSize)
+	if err = db.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	// corrupt the database
+	if err = os.Truncate(path, pageSize); err != nil {
+		t.Fatal(err)
+	}
+
+	db, err = bolt.Open(path, 0666, nil)
+	if err == nil || err.Error() != "file size too small" {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// TestDB_Open_InitialMmapSize tests if having InitialMmapSize large enough
+// to hold data from concurrent write transaction resolves the issue that
+// read transaction blocks the write transaction and causes deadlock.
+// This is a very hacky test since the mmap size is not exposed.
+func TestDB_Open_InitialMmapSize(t *testing.T) {
+	path := tempfile()
+	defer os.Remove(path)
+
+	initMmapSize := 1 << 30  // 1GB
+	testWriteSize := 1 << 27 // 134MB
+
+	db, err := bolt.Open(path, 0666, &bolt.Options{InitialMmapSize: initMmapSize})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// create a long-running read transaction
+	// that never gets closed while writing
+	rtx, err := db.Begin(false)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// create a write transaction
+	wtx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	b, err := wtx.CreateBucket([]byte("test"))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// and commit a large write
+	err = b.Put([]byte("foo"), make([]byte, testWriteSize))
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	done := make(chan struct{})
+
+	go func() {
+		if err := wtx.Commit(); err != nil {
+			t.Fatal(err)
+		}
+		done <- struct{}{}
+	}()
+
+	select {
+	case <-time.After(5 * time.Second):
+		t.Errorf("unexpected that the reader blocks writer")
+	case <-done:
+	}
+
+	if err := rtx.Rollback(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// TestDB_Open_ReadOnly checks a database in read only mode can read but not write.
+func TestDB_Open_ReadOnly(t *testing.T) {
+	// Create a writable db, write k-v and close it.
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	f := db.f
+	o := &bolt.Options{ReadOnly: true}
+	readOnlyDB, err := bolt.Open(f, 0666, o)
+	if err != nil {
+		panic(err)
+	}
+
+	if !readOnlyDB.IsReadOnly() {
+		t.Fatal("expect db in read only mode")
+	}
+
+	// Read from a read-only transaction.
+	if err := readOnlyDB.View(func(tx *bolt.Tx) error {
+		value := tx.Bucket([]byte("widgets")).Get([]byte("foo"))
+		if !bytes.Equal(value, []byte("bar")) {
+			t.Fatal("expect value 'bar', got", value)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Can't launch read-write transaction.
+	if _, err := readOnlyDB.Begin(true); err != bolt.ErrDatabaseReadOnly {
+		t.Fatalf("unexpected error: %s", err)
+	}
+
+	if err := readOnlyDB.Close(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// TestOpen_BigPage checks the database uses bigger pages when
+// changing PageSize.
+func TestOpen_BigPage(t *testing.T) {
+	pageSize := os.Getpagesize()
+
+	db1 := MustOpenWithOption(&bolt.Options{PageSize: pageSize * 2})
+	defer db1.MustClose()
+
+	db2 := MustOpenWithOption(&bolt.Options{PageSize: pageSize * 4})
+	defer db2.MustClose()
+
+	if db1sz, db2sz := fileSize(db1.f), fileSize(db2.f); db1sz >= db2sz {
+		t.Errorf("expected %d < %d", db1sz, db2sz)
+	}
+}
+
+// TestOpen_RecoverFreeList tests opening the DB with free-list
+// write-out after no free list sync will recover the free list
+// and write it out.
+func TestOpen_RecoverFreeList(t *testing.T) {
+	db := MustOpenWithOption(&bolt.Options{NoFreelistSync: true})
+	defer db.MustClose()
+
+	// Write some pages.
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+	wbuf := make([]byte, 8192)
+	for i := 0; i < 100; i++ {
+		s := fmt.Sprintf("%d", i)
+		b, err := tx.CreateBucket([]byte(s))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err = b.Put([]byte(s), wbuf); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err = tx.Commit(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Generate free pages.
+	if tx, err = db.Begin(true); err != nil {
+		t.Fatal(err)
+	}
+	for i := 0; i < 50; i++ {
+		s := fmt.Sprintf("%d", i)
+		b := tx.Bucket([]byte(s))
+		if b == nil {
+			t.Fatal(err)
+		}
+		if err := b.Delete([]byte(s)); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err := tx.Commit(); err != nil {
+		t.Fatal(err)
+	}
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Record freelist count from opening with NoFreelistSync.
+	db.MustReopen()
+	freepages := db.Stats().FreePageN
+	if freepages == 0 {
+		t.Fatalf("no free pages on NoFreelistSync reopen")
+	}
+	if err := db.DB.Close(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Check free page count is reconstructed when opened with freelist sync.
+	db.o = &bolt.Options{}
+	db.MustReopen()
+	// One less free page for syncing the free list on open.
+	freepages--
+	if fp := db.Stats().FreePageN; fp < freepages {
+		t.Fatalf("closed with %d free pages, opened with %d", freepages, fp)
+	}
+}
+
+// Ensure that a database cannot open a transaction when it's not open.
+func TestDB_Begin_ErrDatabaseNotOpen(t *testing.T) {
+	var db bolt.DB
+	if _, err := db.Begin(false); err != bolt.ErrDatabaseNotOpen {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure that a read-write transaction can be retrieved.
+func TestDB_BeginRW(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	} else if tx == nil {
+		t.Fatal("expected tx")
+	}
+
+	if tx.DB() != db.DB {
+		t.Fatal("unexpected tx database")
+	} else if !tx.Writable() {
+		t.Fatal("expected writable tx")
+	}
+
+	if err := tx.Commit(); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// TestDB_Concurrent_WriteTo checks that issuing WriteTo operations concurrently
+// with commits does not produce corrupted db files.
+func TestDB_Concurrent_WriteTo(t *testing.T) {
+	o := &bolt.Options{NoFreelistSync: false}
+	db := MustOpenWithOption(o)
+	defer db.MustClose()
+
+	var wg sync.WaitGroup
+	wtxs, rtxs := 5, 5
+	wg.Add(wtxs * rtxs)
+	f := func(tx *bolt.Tx) {
+		defer wg.Done()
+		f, err := ioutil.TempFile("", "bolt-")
+		if err != nil {
+			panic(err)
+		}
+		time.Sleep(time.Duration(rand.Intn(20)+1) * time.Millisecond)
+		tx.WriteTo(f)
+		tx.Rollback()
+		f.Close()
+		snap := &DB{nil, f.Name(), o}
+		snap.MustReopen()
+		defer snap.MustClose()
+		snap.MustCheck()
+	}
+
+	tx1, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := tx1.CreateBucket([]byte("abc")); err != nil {
+		t.Fatal(err)
+	}
+	if err := tx1.Commit(); err != nil {
+		t.Fatal(err)
+	}
+
+	for i := 0; i < wtxs; i++ {
+		tx, err := db.Begin(true)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := tx.Bucket([]byte("abc")).Put([]byte{0}, []byte{0}); err != nil {
+			t.Fatal(err)
+		}
+		for j := 0; j < rtxs; j++ {
+			rtx, rerr := db.Begin(false)
+			if rerr != nil {
+				t.Fatal(rerr)
+			}
+			go f(rtx)
+		}
+		if err := tx.Commit(); err != nil {
+			t.Fatal(err)
+		}
+	}
+	wg.Wait()
+}
+
+// Ensure that opening a transaction while the DB is closed returns an error.
+func TestDB_BeginRW_Closed(t *testing.T) {
+	var db bolt.DB
+	if _, err := db.Begin(true); err != bolt.ErrDatabaseNotOpen {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+func TestDB_Close_PendingTx_RW(t *testing.T) { testDB_Close_PendingTx(t, true) }
+func TestDB_Close_PendingTx_RO(t *testing.T) { testDB_Close_PendingTx(t, false) }
+
+// Ensure that a database cannot close while transactions are open.
+func testDB_Close_PendingTx(t *testing.T, writable bool) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Start transaction.
+	tx, err := db.Begin(true)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	// Open update in separate goroutine.
+	done := make(chan struct{})
+	go func() {
+		if err := db.Close(); err != nil {
+			t.Fatal(err)
+		}
+		close(done)
+	}()
+
+	// Ensure database hasn't closed.
+	time.Sleep(100 * time.Millisecond)
+	select {
+	case <-done:
+		t.Fatal("database closed too early")
+	default:
+	}
+
+	// Commit transaction.
+	if err := tx.Commit(); err != nil {
+		t.Fatal(err)
+	}
+
+	// Ensure database closed now.
+	time.Sleep(100 * time.Millisecond)
+	select {
+	case <-done:
+	default:
+		t.Fatal("database did not close")
+	}
+}
+
+// Ensure a database can provide a transactional block.
+func TestDB_Update(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		b, err := tx.CreateBucket([]byte("widgets"))
+		if err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("foo"), []byte("bar")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Put([]byte("baz"), []byte("bat")); err != nil {
+			t.Fatal(err)
+		}
+		if err := b.Delete([]byte("foo")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		if v := b.Get([]byte("foo")); v != nil {
+			t.Fatalf("expected nil value, got: %v", v)
+		}
+		if v := b.Get([]byte("baz")); !bytes.Equal(v, []byte("bat")) {
+			t.Fatalf("unexpected value: %v", v)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a closed database returns an error while running a transaction block
+func TestDB_Update_Closed(t *testing.T) {
+	var db bolt.DB
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != bolt.ErrDatabaseNotOpen {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure a panic occurs while trying to commit a managed transaction.
+func TestDB_Update_ManualCommit(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var panicked bool
+	if err := db.Update(func(tx *bolt.Tx) error {
+		func() {
+			defer func() {
+				if r := recover(); r != nil {
+					panicked = true
+				}
+			}()
+
+			if err := tx.Commit(); err != nil {
+				t.Fatal(err)
+			}
+		}()
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	} else if !panicked {
+		t.Fatal("expected panic")
+	}
+}
+
+// Ensure a panic occurs while trying to rollback a managed transaction.
+func TestDB_Update_ManualRollback(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var panicked bool
+	if err := db.Update(func(tx *bolt.Tx) error {
+		func() {
+			defer func() {
+				if r := recover(); r != nil {
+					panicked = true
+				}
+			}()
+
+			if err := tx.Rollback(); err != nil {
+				t.Fatal(err)
+			}
+		}()
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	} else if !panicked {
+		t.Fatal("expected panic")
+	}
+}
+
+// Ensure a panic occurs while trying to commit a managed transaction.
+func TestDB_View_ManualCommit(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var panicked bool
+	if err := db.View(func(tx *bolt.Tx) error {
+		func() {
+			defer func() {
+				if r := recover(); r != nil {
+					panicked = true
+				}
+			}()
+
+			if err := tx.Commit(); err != nil {
+				t.Fatal(err)
+			}
+		}()
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	} else if !panicked {
+		t.Fatal("expected panic")
+	}
+}
+
+// Ensure a panic occurs while trying to rollback a managed transaction.
+func TestDB_View_ManualRollback(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var panicked bool
+	if err := db.View(func(tx *bolt.Tx) error {
+		func() {
+			defer func() {
+				if r := recover(); r != nil {
+					panicked = true
+				}
+			}()
+
+			if err := tx.Rollback(); err != nil {
+				t.Fatal(err)
+			}
+		}()
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	} else if !panicked {
+		t.Fatal("expected panic")
+	}
+}
+
+// Ensure a write transaction that panics does not hold open locks.
+func TestDB_Update_Panic(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	// Panic during update but recover.
+	func() {
+		defer func() {
+			if r := recover(); r != nil {
+				t.Log("recover: update", r)
+			}
+		}()
+
+		if err := db.Update(func(tx *bolt.Tx) error {
+			if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+				t.Fatal(err)
+			}
+			panic("omg")
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}()
+
+	// Verify we can update again.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Verify that our change persisted.
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if tx.Bucket([]byte("widgets")) == nil {
+			t.Fatal("expected bucket")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure a database can return an error through a read-only transactional block.
+func TestDB_View_Error(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.View(func(tx *bolt.Tx) error {
+		return errors.New("xxx")
+	}); err == nil || err.Error() != "xxx" {
+		t.Fatalf("unexpected error: %s", err)
+	}
+}
+
+// Ensure a read transaction that panics does not hold open locks.
+func TestDB_View_Panic(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Panic during view transaction but recover.
+	func() {
+		defer func() {
+			if r := recover(); r != nil {
+				t.Log("recover: view", r)
+			}
+		}()
+
+		if err := db.View(func(tx *bolt.Tx) error {
+			if tx.Bucket([]byte("widgets")) == nil {
+				t.Fatal("expected bucket")
+			}
+			panic("omg")
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}()
+
+	// Verify that we can still use read transactions.
+	if err := db.View(func(tx *bolt.Tx) error {
+		if tx.Bucket([]byte("widgets")) == nil {
+			t.Fatal("expected bucket")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that DB stats can be returned.
+func TestDB_Stats(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		_, err := tx.CreateBucket([]byte("widgets"))
+		return err
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	stats := db.Stats()
+	if stats.TxStats.PageCount != 2 {
+		t.Fatalf("unexpected TxStats.PageCount: %d", stats.TxStats.PageCount)
+	} else if stats.FreePageN != 0 {
+		t.Fatalf("unexpected FreePageN != 0: %d", stats.FreePageN)
+	} else if stats.PendingPageN != 2 {
+		t.Fatalf("unexpected PendingPageN != 2: %d", stats.PendingPageN)
+	}
+}
+
+// Ensure that database pages are in expected order and type.
+func TestDB_Consistency(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+	if err := db.Update(func(tx *bolt.Tx) error {
+		_, err := tx.CreateBucket([]byte("widgets"))
+		return err
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	for i := 0; i < 10; i++ {
+		if err := db.Update(func(tx *bolt.Tx) error {
+			if err := tx.Bucket([]byte("widgets")).Put([]byte("foo"), []byte("bar")); err != nil {
+				t.Fatal(err)
+			}
+			return nil
+		}); err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if p, _ := tx.Page(0); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "meta" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(1); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "meta" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(2); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "free" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(3); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "free" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(4); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "leaf" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(5); p == nil {
+			t.Fatal("expected page")
+		} else if p.Type != "freelist" {
+			t.Fatalf("unexpected page type: %s", p.Type)
+		}
+
+		if p, _ := tx.Page(6); p != nil {
+			t.Fatal("unexpected page")
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+// Ensure that DB stats can be subtracted from one another.
+func TestDBStats_Sub(t *testing.T) {
+	var a, b bolt.Stats
+	a.TxStats.PageCount = 3
+	a.FreePageN = 4
+	b.TxStats.PageCount = 10
+	b.FreePageN = 14
+	diff := b.Sub(&a)
+	if diff.TxStats.PageCount != 7 {
+		t.Fatalf("unexpected TxStats.PageCount: %d", diff.TxStats.PageCount)
+	}
+
+	// free page stats are copied from the receiver and not subtracted
+	if diff.FreePageN != 14 {
+		t.Fatalf("unexpected FreePageN: %d", diff.FreePageN)
+	}
+}
+
+// Ensure two functions can perform updates in a single batch.
+func TestDB_Batch(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	if err := db.Update(func(tx *bolt.Tx) error {
+		if _, err := tx.CreateBucket([]byte("widgets")); err != nil {
+			t.Fatal(err)
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+
+	// Iterate over multiple updates in separate goroutines.
+	n := 2
+	ch := make(chan error)
+	for i := 0; i < n; i++ {
+		go func(i int) {
+			ch <- db.Batch(func(tx *bolt.Tx) error {
+				return tx.Bucket([]byte("widgets")).Put(u64tob(uint64(i)), []byte{})
+			})
+		}(i)
+	}
+
+	// Check all responses to make sure there's no error.
+	for i := 0; i < n; i++ {
+		if err := <-ch; err != nil {
+			t.Fatal(err)
+		}
+	}
+
+	// Ensure data is correct.
+	if err := db.View(func(tx *bolt.Tx) error {
+		b := tx.Bucket([]byte("widgets"))
+		for i := 0; i < n; i++ {
+			if v := b.Get(u64tob(uint64(i))); v == nil {
+				t.Errorf("key not found: %d", i)
+			}
+		}
+		return nil
+	}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestDB_Batch_Panic(t *testing.T) {
+	db := MustOpenDB()
+	defer db.MustClose()
+
+	var sentinel int
+	var bork = &sentinel
+	var problem interface{}
+	var err error
+
+	// Execute a function inside a batch that panics.
+	func() {
+		defer func() {
+			if p := recover(); p != nil {
+				problem = p
+			}
+		}()
+		err = db.Batch(func(tx *bolt.Tx) error {
+			panic(bork)
+		})
+	}()
+

  (This diff was longer than 20,000 lines, and has been truncated...)


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services