ca.go 18 KB

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