database: add documentation, reference new utils functions

This commit is contained in:
Cadey Ratio 2017-01-19 16:28:38 -08:00
parent f7df55f044
commit 244ebfda04
1 changed files with 12 additions and 7 deletions

View File

@ -2,17 +2,18 @@ package database
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"git.xeserv.us/xena/route/routerpc"
"git.xeserv.us/xena/route/utils"
r "github.com/GoRethink/gorethink"
)
// DB is the high level wrapper to the datastore.
type DB struct {
s *r.Session
}
// New takes a rethinkdb host and databasea and sets up a connection.
func New(host, database string) (*DB, error) {
session, err := r.Connect(r.ConnectOpts{
Address: host,
@ -34,6 +35,7 @@ var tables = []string{
"routes",
}
// Route is a single route object serialized to rethinkdb.
type Route struct {
ID string `gorethink:"id,omitempty"`
Hostname string `gorethink:"hostname"`
@ -42,12 +44,9 @@ type Route struct {
OnionKey []byte `gorethink:"onionKey"` // PEM-encoded
}
// SaveRoute adds the route to the database.
func (db *DB) SaveRoute(resp *routerpc.AddHostResponse) error {
pemblock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(resp.PrivKey.(*rsa.PrivateKey)),
}
bytes := pem.EncodeToMemory(pemblock)
bytes := utils.RSAPrivateKeyToPem(resp.PrivKey.(*rsa.PrivateKey))
rt := &Route{
Hostname: resp.Hostname,
@ -56,6 +55,9 @@ func (db *DB) SaveRoute(resp *routerpc.AddHostResponse) error {
OnionKey: bytes,
}
// TODO: check if OnionHostname or Hostname actually exists in
// the database. RethinkDB doesn't support unique secondary indexes.
_, err := r.Table("routes").Insert(rt).RunWrite(db.s)
if err != nil {
return err
@ -64,6 +66,9 @@ func (db *DB) SaveRoute(resp *routerpc.AddHostResponse) error {
return nil
}
// GetAllRoutes fetches all of the route entries from the database
// and returns them. This is intended for the startup process or
// admin tooling.
func (db *DB) GetAllRoutes() ([]Route, error) {
rows, err := r.Table("routes").Run(db.s)
if err != nil {