github.com/ztalab/ZACA@v0.0.1/pkg/caclient/rorate_controller.go (about)

     1  package caclient
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/ztalab/cfssl/transport/roots"
     7  	"go.uber.org/zap"
     8  )
     9  
    10  // RotateController ...
    11  type RotateController struct {
    12  	transport   *Transport
    13  	rotateAfter time.Duration
    14  	logger      *zap.SugaredLogger
    15  }
    16  
    17  // Run ...
    18  func (rc *RotateController) Run() {
    19  	log := rc.logger
    20  	ticker := time.NewTicker(60 * time.Minute)
    21  	defer func() {
    22  		ticker.Stop()
    23  	}()
    24  	for {
    25  		select {
    26  		case <-ticker.C:
    27  			// Automatically update certificates
    28  			err := rc.transport.AutoUpdate()
    29  			if err != nil {
    30  				log.Errorf("Certificate rotation failed: %v", err)
    31  			}
    32  			rc.AddCert()
    33  		}
    34  	}
    35  }
    36  
    37  func (rc *RotateController) AddCert() {
    38  	log := rc.logger
    39  	store, err := roots.New(rc.transport.Identity.Roots)
    40  	if err != nil {
    41  		log.Errorf("Failed to get roots: %v", err)
    42  		return
    43  	}
    44  	rc.transport.TrustStore.AddCerts(store.Certificates())
    45  
    46  	if len(rc.transport.Identity.ClientRoots) > 0 {
    47  		store, err = roots.New(rc.transport.Identity.ClientRoots)
    48  		if err != nil {
    49  			log.Errorf("Failed to get client roots: %v", err)
    50  			return
    51  		}
    52  		rc.transport.ClientTrustStore.AddCerts(store.Certificates())
    53  	}
    54  	return
    55  }