nosql.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package nosql
  2. import (
  3. "context"
  4. "encoding/json"
  5. "time"
  6. "github.com/pkg/errors"
  7. nosqlDB "github.com/smallstep/nosql/database"
  8. "go.step.sm/crypto/randutil"
  9. )
  10. var (
  11. adminsTable = []byte("admins")
  12. provisionersTable = []byte("provisioners")
  13. authorityPoliciesTable = []byte("authority_policies")
  14. )
  15. // DB is a struct that implements the AdminDB interface.
  16. type DB struct {
  17. db nosqlDB.DB
  18. authorityID string
  19. }
  20. // New configures and returns a new Authority DB backend implemented using a nosql DB.
  21. func New(db nosqlDB.DB, authorityID string) (*DB, error) {
  22. tables := [][]byte{adminsTable, provisionersTable, authorityPoliciesTable}
  23. for _, b := range tables {
  24. if err := db.CreateTable(b); err != nil {
  25. return nil, errors.Wrapf(err, "error creating table %s",
  26. string(b))
  27. }
  28. }
  29. return &DB{db, authorityID}, nil
  30. }
  31. // save writes the new data to the database, overwriting the old data if it
  32. // existed.
  33. func (db *DB) save(_ context.Context, id string, nu, old interface{}, typ string, table []byte) error {
  34. var (
  35. err error
  36. newB []byte
  37. )
  38. if nu == nil {
  39. newB = nil
  40. } else {
  41. newB, err = json.Marshal(nu)
  42. if err != nil {
  43. return errors.Wrapf(err, "error marshaling authority type: %s, value: %v", typ, nu)
  44. }
  45. }
  46. var oldB []byte
  47. if old == nil {
  48. oldB = nil
  49. } else {
  50. oldB, err = json.Marshal(old)
  51. if err != nil {
  52. return errors.Wrapf(err, "error marshaling admin type: %s, value: %v", typ, old)
  53. }
  54. }
  55. _, swapped, err := db.db.CmpAndSwap(table, []byte(id), oldB, newB)
  56. switch {
  57. case err != nil:
  58. return errors.Wrapf(err, "error saving authority %s", typ)
  59. case !swapped:
  60. return errors.Errorf("error saving authority %s; changed since last read", typ)
  61. default:
  62. return nil
  63. }
  64. }
  65. func randID() (val string, err error) {
  66. val, err = randutil.UUIDv4()
  67. if err != nil {
  68. return "", errors.Wrap(err, "error generating random alphanumeric ID")
  69. }
  70. return val, nil
  71. }
  72. // Clock that returns time in UTC rounded to seconds.
  73. type Clock struct{}
  74. // Now returns the UTC time rounded to seconds.
  75. func (c *Clock) Now() time.Time {
  76. return time.Now().UTC().Truncate(time.Second)
  77. }
  78. var clock = new(Clock)