nosql.go 2.0 KB

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