ca.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "fmt"
  8. "log"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/go-chi/chi"
  17. "github.com/go-chi/chi/middleware"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/acme"
  20. acmeAPI "github.com/smallstep/certificates/acme/api"
  21. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  22. "github.com/smallstep/certificates/api"
  23. "github.com/smallstep/certificates/authority"
  24. "github.com/smallstep/certificates/authority/admin"
  25. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  26. "github.com/smallstep/certificates/authority/config"
  27. "github.com/smallstep/certificates/db"
  28. "github.com/smallstep/certificates/logging"
  29. "github.com/smallstep/certificates/monitoring"
  30. "github.com/smallstep/certificates/scep"
  31. scepAPI "github.com/smallstep/certificates/scep/api"
  32. "github.com/smallstep/certificates/server"
  33. "github.com/smallstep/nosql"
  34. "go.step.sm/cli-utils/step"
  35. "go.step.sm/crypto/x509util"
  36. )
  37. type options struct {
  38. configFile string
  39. linkedCAToken string
  40. quiet bool
  41. password []byte
  42. issuerPassword []byte
  43. sshHostPassword []byte
  44. sshUserPassword []byte
  45. database db.AuthDB
  46. }
  47. func (o *options) apply(opts []Option) {
  48. for _, fn := range opts {
  49. fn(o)
  50. }
  51. }
  52. // Option is the type of options passed to the CA constructor.
  53. type Option func(o *options)
  54. // WithConfigFile sets the given name as the configuration file name in the CA
  55. // options.
  56. func WithConfigFile(name string) Option {
  57. return func(o *options) {
  58. o.configFile = name
  59. }
  60. }
  61. // WithPassword sets the given password as the configured password in the CA
  62. // options.
  63. func WithPassword(password []byte) Option {
  64. return func(o *options) {
  65. o.password = password
  66. }
  67. }
  68. // WithSSHHostPassword sets the given password to decrypt the key used to sign
  69. // ssh host certificates.
  70. func WithSSHHostPassword(password []byte) Option {
  71. return func(o *options) {
  72. o.sshHostPassword = password
  73. }
  74. }
  75. // WithSSHUserPassword sets the given password to decrypt the key used to sign
  76. // ssh user certificates.
  77. func WithSSHUserPassword(password []byte) Option {
  78. return func(o *options) {
  79. o.sshUserPassword = password
  80. }
  81. }
  82. // WithIssuerPassword sets the given password as the configured certificate
  83. // issuer password in the CA options.
  84. func WithIssuerPassword(password []byte) Option {
  85. return func(o *options) {
  86. o.issuerPassword = password
  87. }
  88. }
  89. // WithDatabase sets the given authority database to the CA options.
  90. func WithDatabase(d db.AuthDB) Option {
  91. return func(o *options) {
  92. o.database = d
  93. }
  94. }
  95. // WithLinkedCAToken sets the token used to authenticate with the linkedca.
  96. func WithLinkedCAToken(token string) Option {
  97. return func(o *options) {
  98. o.linkedCAToken = token
  99. }
  100. }
  101. // WithQuiet sets the quiet flag.
  102. func WithQuiet(quiet bool) Option {
  103. return func(o *options) {
  104. o.quiet = quiet
  105. }
  106. }
  107. // CA is the type used to build the complete certificate authority. It builds
  108. // the HTTP server, set ups the middlewares and the HTTP handlers.
  109. type CA struct {
  110. auth *authority.Authority
  111. config *config.Config
  112. srv *server.Server
  113. insecureSrv *server.Server
  114. opts *options
  115. renewer *TLSRenewer
  116. compactStop chan struct{}
  117. }
  118. // New creates and initializes the CA with the given configuration and options.
  119. func New(cfg *config.Config, opts ...Option) (*CA, error) {
  120. ca := &CA{
  121. config: cfg,
  122. opts: new(options),
  123. compactStop: make(chan struct{}),
  124. }
  125. ca.opts.apply(opts)
  126. return ca.Init(cfg)
  127. }
  128. // Init initializes the CA with the given configuration.
  129. func (ca *CA) Init(cfg *config.Config) (*CA, error) {
  130. // Set password, it's ok to set nil password, the ca will prompt for them if
  131. // they are required.
  132. opts := []authority.Option{
  133. authority.WithPassword(ca.opts.password),
  134. authority.WithSSHHostPassword(ca.opts.sshHostPassword),
  135. authority.WithSSHUserPassword(ca.opts.sshUserPassword),
  136. authority.WithIssuerPassword(ca.opts.issuerPassword),
  137. }
  138. if ca.opts.linkedCAToken != "" {
  139. opts = append(opts, authority.WithLinkedCAToken(ca.opts.linkedCAToken))
  140. }
  141. if ca.opts.database != nil {
  142. opts = append(opts, authority.WithDatabase(ca.opts.database))
  143. }
  144. if ca.opts.quiet {
  145. opts = append(opts, authority.WithQuietInit())
  146. }
  147. webhookTransport := http.DefaultTransport.(*http.Transport).Clone()
  148. opts = append(opts, authority.WithWebhookClient(&http.Client{Transport: webhookTransport}))
  149. auth, err := authority.New(cfg, opts...)
  150. if err != nil {
  151. return nil, err
  152. }
  153. ca.auth = auth
  154. tlsConfig, clientTLSConfig, err := ca.getTLSConfig(auth)
  155. if err != nil {
  156. return nil, err
  157. }
  158. webhookTransport.TLSClientConfig = clientTLSConfig
  159. // Using chi as the main router
  160. mux := chi.NewRouter()
  161. handler := http.Handler(mux)
  162. insecureMux := chi.NewRouter()
  163. insecureHandler := http.Handler(insecureMux)
  164. // Add HEAD middleware
  165. mux.Use(middleware.GetHead)
  166. insecureMux.Use(middleware.GetHead)
  167. // Add regular CA api endpoints in / and /1.0
  168. api.Route(mux)
  169. mux.Route("/1.0", func(r chi.Router) {
  170. api.Route(r)
  171. })
  172. // Mount the CRL to the insecure mux
  173. insecureMux.Get("/crl", api.CRL)
  174. insecureMux.Get("/1.0/crl", api.CRL)
  175. // Add ACME api endpoints in /acme and /1.0/acme
  176. dns := cfg.DNSNames[0]
  177. u, err := url.Parse("https://" + cfg.Address)
  178. if err != nil {
  179. return nil, err
  180. }
  181. port := u.Port()
  182. if port != "" && port != "443" {
  183. dns = fmt.Sprintf("%s:%s", dns, port)
  184. }
  185. // ACME Router is only available if we have a database.
  186. var acmeDB acme.DB
  187. var acmeLinker acme.Linker
  188. if cfg.DB != nil {
  189. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  190. if err != nil {
  191. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  192. }
  193. acmeLinker = acme.NewLinker(dns, "acme")
  194. mux.Route("/acme", func(r chi.Router) {
  195. acmeAPI.Route(r)
  196. })
  197. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  198. // of the ACME spec.
  199. mux.Route("/2.0/acme", func(r chi.Router) {
  200. acmeAPI.Route(r)
  201. })
  202. }
  203. // Admin API Router
  204. if cfg.AuthorityConfig.EnableAdmin {
  205. adminDB := auth.GetAdminDatabase()
  206. if adminDB != nil {
  207. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  208. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  209. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  210. mux.Route("/admin", func(r chi.Router) {
  211. adminAPI.Route(
  212. r,
  213. adminAPI.WithACMEResponder(acmeAdminResponder),
  214. adminAPI.WithPolicyResponder(policyAdminResponder),
  215. adminAPI.WithWebhookResponder(webhookAdminResponder),
  216. )
  217. })
  218. }
  219. }
  220. var scepAuthority *scep.Authority
  221. if ca.shouldServeSCEPEndpoints() {
  222. // validate the SCEP authority configuration. Currently this
  223. // will not result in a failure to start if one or more SCEP
  224. // provisioners are not correctly configured. Only a log will
  225. // be emitted.
  226. scepAuthority = auth.GetSCEP()
  227. if err := scepAuthority.Validate(); err != nil {
  228. err = errors.Wrap(err, "failed validating SCEP authority")
  229. shouldFail := false
  230. if shouldFail {
  231. return nil, err
  232. }
  233. log.Println(err)
  234. }
  235. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  236. // SCEP operations are performed using HTTP, so that's why the API is mounted
  237. // to the insecure mux.
  238. scepPrefix := "scep"
  239. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  240. scepAPI.Route(r)
  241. })
  242. // The RFC also mentions usage of HTTPS, but seems to advise
  243. // against it, because of potential interoperability issues.
  244. // Currently I think it's not bad to use HTTPS also, so that's
  245. // why I've kept the API endpoints in both muxes and both HTTP
  246. // as well as HTTPS can be used to request certificates
  247. // using SCEP.
  248. mux.Route("/"+scepPrefix, func(r chi.Router) {
  249. scepAPI.Route(r)
  250. })
  251. }
  252. // helpful routine for logging all routes
  253. //dumpRoutes(mux)
  254. //dumpRoutes(insecureMux)
  255. // Add monitoring if configured
  256. if len(cfg.Monitoring) > 0 {
  257. m, err := monitoring.New(cfg.Monitoring)
  258. if err != nil {
  259. return nil, err
  260. }
  261. handler = m.Middleware(handler)
  262. insecureHandler = m.Middleware(insecureHandler)
  263. }
  264. // Add logger if configured
  265. if len(cfg.Logger) > 0 {
  266. logger, err := logging.New("ca", cfg.Logger)
  267. if err != nil {
  268. return nil, err
  269. }
  270. handler = logger.Middleware(handler)
  271. insecureHandler = logger.Middleware(insecureHandler)
  272. }
  273. // Create context with all the necessary values.
  274. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  275. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  276. ca.srv.BaseContext = func(net.Listener) context.Context {
  277. return baseContext
  278. }
  279. // only start the insecure server if the insecure address is configured
  280. // and, currently, also only when it should serve SCEP endpoints.
  281. if ca.shouldServeInsecureServer() {
  282. // TODO: instead opt for having a single server.Server but two
  283. // http.Servers handling the HTTP and HTTPS handler? The latter
  284. // will probably introduce more complexity in terms of graceful
  285. // reload.
  286. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  287. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  288. return baseContext
  289. }
  290. }
  291. return ca, nil
  292. }
  293. // shouldServeInsecureServer returns whether or not the insecure
  294. // server should also be started. This is (currently) only the case
  295. // if the insecure address has been configured AND when a SCEP
  296. // provisioner is configured or when a CRL is configured.
  297. func (ca *CA) shouldServeInsecureServer() bool {
  298. switch {
  299. case ca.config.InsecureAddress == "":
  300. return false
  301. case ca.shouldServeSCEPEndpoints():
  302. return true
  303. case ca.config.CRL.IsEnabled():
  304. return true
  305. default:
  306. return false
  307. }
  308. }
  309. // buildContext builds the server base context.
  310. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  311. ctx := authority.NewContext(context.Background(), a)
  312. if authDB := a.GetDatabase(); authDB != nil {
  313. ctx = db.NewContext(ctx, authDB)
  314. }
  315. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  316. ctx = admin.NewContext(ctx, adminDB)
  317. }
  318. if scepAuthority != nil {
  319. ctx = scep.NewContext(ctx, scepAuthority)
  320. }
  321. if acmeDB != nil {
  322. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  323. }
  324. return ctx
  325. }
  326. // Run starts the CA calling to the server ListenAndServe method.
  327. func (ca *CA) Run() error {
  328. var wg sync.WaitGroup
  329. errs := make(chan error, 1)
  330. if !ca.opts.quiet {
  331. authorityInfo := ca.auth.GetInfo()
  332. log.Printf("Starting %s", step.Version())
  333. log.Printf("Documentation: https://u.step.sm/docs/ca")
  334. log.Printf("Community Discord: https://u.step.sm/discord")
  335. if step.Contexts().GetCurrent() != nil {
  336. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  337. }
  338. log.Printf("Config file: %s", ca.getConfigFileOutput())
  339. baseURL := fmt.Sprintf("https://%s%s",
  340. authorityInfo.DNSNames[0],
  341. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  342. log.Printf("The primary server URL is %s", baseURL)
  343. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  344. if len(authorityInfo.DNSNames) > 1 {
  345. log.Printf("Additional configured hostnames: %s",
  346. strings.Join(authorityInfo.DNSNames[1:], ", "))
  347. }
  348. for _, crt := range authorityInfo.RootX509Certs {
  349. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  350. }
  351. if authorityInfo.SSHCAHostPublicKey != nil {
  352. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  353. }
  354. if authorityInfo.SSHCAUserPublicKey != nil {
  355. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  356. }
  357. }
  358. wg.Add(1)
  359. go func() {
  360. defer wg.Done()
  361. ca.runCompactJob()
  362. }()
  363. if ca.insecureSrv != nil {
  364. wg.Add(1)
  365. go func() {
  366. defer wg.Done()
  367. errs <- ca.insecureSrv.ListenAndServe()
  368. }()
  369. }
  370. wg.Add(1)
  371. go func() {
  372. defer wg.Done()
  373. errs <- ca.srv.ListenAndServe()
  374. }()
  375. // wait till error occurs; ensures the servers keep listening
  376. err := <-errs
  377. wg.Wait()
  378. return err
  379. }
  380. // Stop stops the CA calling to the server Shutdown method.
  381. func (ca *CA) Stop() error {
  382. close(ca.compactStop)
  383. ca.renewer.Stop()
  384. if err := ca.auth.Shutdown(); err != nil {
  385. log.Printf("error stopping ca.Authority: %+v\n", err)
  386. }
  387. var insecureShutdownErr error
  388. if ca.insecureSrv != nil {
  389. insecureShutdownErr = ca.insecureSrv.Shutdown()
  390. }
  391. secureErr := ca.srv.Shutdown()
  392. if insecureShutdownErr != nil {
  393. return insecureShutdownErr
  394. }
  395. return secureErr
  396. }
  397. // Reload reloads the configuration of the CA and calls to the server Reload
  398. // method.
  399. func (ca *CA) Reload() error {
  400. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  401. if err != nil {
  402. return errors.Wrap(err, "error reloading ca configuration")
  403. }
  404. logContinue := func(reason string) {
  405. log.Println(reason)
  406. log.Println("Continuing to run with the original configuration.")
  407. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  408. }
  409. // Do not allow reload if the database configuration has changed.
  410. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  411. logContinue("Reload failed because the database configuration has changed.")
  412. return errors.New("error reloading ca: database configuration cannot change")
  413. }
  414. newCA, err := New(cfg,
  415. WithPassword(ca.opts.password),
  416. WithSSHHostPassword(ca.opts.sshHostPassword),
  417. WithSSHUserPassword(ca.opts.sshUserPassword),
  418. WithIssuerPassword(ca.opts.issuerPassword),
  419. WithLinkedCAToken(ca.opts.linkedCAToken),
  420. WithQuiet(ca.opts.quiet),
  421. WithConfigFile(ca.opts.configFile),
  422. WithDatabase(ca.auth.GetDatabase()),
  423. )
  424. if err != nil {
  425. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  426. return errors.Wrap(err, "error reloading ca")
  427. }
  428. if ca.insecureSrv != nil {
  429. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  430. logContinue("Reload failed because insecure server could not be replaced.")
  431. return errors.Wrap(err, "error reloading insecure server")
  432. }
  433. }
  434. if err = ca.srv.Reload(newCA.srv); err != nil {
  435. logContinue("Reload failed because server could not be replaced.")
  436. return errors.Wrap(err, "error reloading server")
  437. }
  438. // 1. Stop previous renewer
  439. // 2. Safely shutdown any internal resources (e.g. key manager)
  440. // 3. Replace ca properties
  441. // Do not replace ca.srv
  442. ca.renewer.Stop()
  443. ca.auth.CloseForReload()
  444. ca.auth = newCA.auth
  445. ca.config = newCA.config
  446. ca.opts = newCA.opts
  447. ca.renewer = newCA.renewer
  448. return nil
  449. }
  450. // get TLSConfig returns separate TLSConfigs for server and client with the
  451. // same self-renewing certificate.
  452. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  453. // Create initial TLS certificate
  454. tlsCrt, err := auth.GetTLSCertificate()
  455. if err != nil {
  456. return nil, nil, err
  457. }
  458. // Start tls renewer with the new certificate.
  459. // If a renewer was started, attempt to stop it before.
  460. if ca.renewer != nil {
  461. ca.renewer.Stop()
  462. }
  463. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  464. if err != nil {
  465. return nil, nil, err
  466. }
  467. ca.renewer.Run()
  468. var serverTLSConfig *tls.Config
  469. if ca.config.TLS != nil {
  470. serverTLSConfig = ca.config.TLS.TLSConfig()
  471. } else {
  472. serverTLSConfig = &tls.Config{
  473. MinVersion: tls.VersionTLS12,
  474. }
  475. }
  476. // GetCertificate will only be called if the client supplies SNI
  477. // information or if tlsConfig.Certificates is empty.
  478. // When client requests are made using an IP address (as opposed to a domain
  479. // name) the server does not receive any SNI and may fallback to using the
  480. // first entry in the Certificates attribute; by setting the attribute to
  481. // empty we are implicitly forcing GetCertificate to be the only mechanism
  482. // by which the server can find it's own leaf Certificate.
  483. serverTLSConfig.Certificates = []tls.Certificate{}
  484. clientTLSConfig := serverTLSConfig.Clone()
  485. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  486. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  487. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  488. certPool := x509.NewCertPool()
  489. // initialize a certificate pool with root CA certificates to trust when connecting
  490. // to webhook servers
  491. rootCAsPool, err := x509.SystemCertPool()
  492. if err != nil {
  493. return nil, nil, err
  494. }
  495. for _, crt := range auth.GetRootCertificates() {
  496. certPool.AddCert(crt)
  497. rootCAsPool.AddCert(crt)
  498. }
  499. // adding the intermediate CA certificates to the pool will allow clients that
  500. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  501. // added here are used when building a certificate chain.
  502. intermediates := tlsCrt.Certificate[1:]
  503. for _, certBytes := range intermediates {
  504. cert, err := x509.ParseCertificate(certBytes)
  505. if err != nil {
  506. return nil, nil, err
  507. }
  508. certPool.AddCert(cert)
  509. rootCAsPool.AddCert(cert)
  510. }
  511. // Add support for mutual tls to renew certificates
  512. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  513. serverTLSConfig.ClientCAs = certPool
  514. clientTLSConfig.RootCAs = rootCAsPool
  515. return serverTLSConfig, clientTLSConfig, nil
  516. }
  517. // shouldServeSCEPEndpoints returns if the CA should be
  518. // configured with endpoints for SCEP. This is assumed to be
  519. // true if a SCEPService exists, which is true in case at
  520. // least one SCEP provisioner was configured.
  521. func (ca *CA) shouldServeSCEPEndpoints() bool {
  522. return ca.auth.GetSCEP() != nil
  523. }
  524. //nolint:unused // useful for debugging
  525. func dumpRoutes(mux chi.Routes) {
  526. // helpful routine for logging all routes
  527. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  528. fmt.Printf("%s %s\n", method, route)
  529. return nil
  530. }
  531. if err := chi.Walk(mux, walkFunc); err != nil {
  532. fmt.Printf("Logging err: %s\n", err.Error())
  533. }
  534. }
  535. func (ca *CA) getConfigFileOutput() string {
  536. if ca.config.WasLoadedFromFile() {
  537. return ca.config.Filepath()
  538. }
  539. return "loaded from token"
  540. }
  541. // runCompactJob will run the value log garbage collector if the nosql database
  542. // supports it.
  543. func (ca *CA) runCompactJob() {
  544. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  545. if !ok {
  546. return
  547. }
  548. compactor, ok := caDB.DB.(nosql.Compactor)
  549. if !ok {
  550. return
  551. }
  552. // Compact database at start.
  553. runCompact(compactor)
  554. // Compact database every minute.
  555. ticker := time.NewTicker(time.Minute)
  556. defer ticker.Stop()
  557. for {
  558. select {
  559. case <-ca.compactStop:
  560. return
  561. case <-ticker.C:
  562. runCompact(compactor)
  563. }
  564. }
  565. }
  566. // runCompact executes the compact job until it returns an error.
  567. func runCompact(c nosql.Compactor) {
  568. for err := error(nil); err == nil; {
  569. err = c.Compact(0.7)
  570. }
  571. }