Skip to content

Commit

Permalink
Switch to Rancher v2 API
Browse files Browse the repository at this point in the history
  • Loading branch information
janeczku committed Jan 28, 2017
1 parent 9686ce1 commit 987123d
Show file tree
Hide file tree
Showing 220 changed files with 6,700 additions and 4,391 deletions.
2 changes: 1 addition & 1 deletion Dockerfile.dev
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ ADD build/rancher-letsencrypt-linux-amd64 /usr/bin/rancher-letsencrypt

RUN chmod +x /usr/bin/rancher-letsencrypt

ENTRYPOINT ["/usr/bin/rancher-letsencrypt", "-debug"]
ENTRYPOINT ["/usr/bin/rancher-letsencrypt", "-debug", "-test-mode"]
14 changes: 8 additions & 6 deletions Godeps/Godeps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion context.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,15 @@ type Context struct {
ExpiryDate time.Time
RancherCertId string

Debug bool
Debug bool
TestMode bool
}

// InitContext initializes the application context from environmental variables
func (c *Context) InitContext() {
var err error
c.Debug = debug
c.TestMode = testMode
cattleUrl := getEnvOption("CATTLE_URL", true)
cattleApiKey := getEnvOption("CATTLE_ACCESS_KEY", true)
cattleSecretKey := getEnvOption("CATTLE_SECRET_KEY", true)
Expand Down Expand Up @@ -94,6 +96,8 @@ func (c *Context) InitContext() {
logrus.Fatalf("LetsEncrypt client: %v", err)
}

logrus.Infof("Using Let's Encrypt %s API", apiVersion)

// Enable debug mode
if c.Debug {
logrus.SetLevel(logrus.DebugLevel)
Expand Down
10 changes: 10 additions & 0 deletions letsencrypt/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type AcmeCertificate struct {
type Client struct {
client *lego.Client
apiVersion ApiVersion
provider Provider
}

// NewClient returns a new Lets Encrypt client
Expand Down Expand Up @@ -140,6 +141,7 @@ func NewClient(email string, kt KeyType, apiVer ApiVersion, provider ProviderOpt
return &Client{
client: client,
apiVersion: apiVer,
provider: provider.Provider,
}, nil
}

Expand Down Expand Up @@ -312,6 +314,14 @@ func (c *Client) ConfigPath() string {
return path
}

func (c *Client) ProviderName() string {
return string(c.provider)
}

func (c *Client) ApiVersion() string {
return string(c.apiVersion)
}

func (c *Client) CertPath(certName string) string {
return path.Join(c.ConfigPath(), "certs", safeFileName(certName))
}
Expand Down
4 changes: 3 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ var (
Version string
Git string

debug bool
debug bool
testMode bool
)

func init() {
flag.BoolVar(&debug, "debug", false, "Enable debugging")
flag.BoolVar(&testMode, "test-mode", false, "Renew certificate every 120 seconds")
logrus.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true})
logrus.SetOutput(os.Stdout)
}
Expand Down
19 changes: 13 additions & 6 deletions manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,14 @@ func (c *Context) startup() {
return
}

logrus.Infof("Trying to obtain SSL certificate (%s) from Let's Encrypt CA", strings.Join(c.Domains, ","))
if c.Acme.ProviderName() == "HTTP" {
logrus.Info("Using HTTP challenge: Sleeping for 120 seconds before requesting certificate")
logrus.Info("Make sure that HTTP requests for '/.well-known/acme-challenge' for all certificate " +
"domains are forwarded to the container running this application")
time.Sleep(120 * time.Second)
}

logrus.Infof("Trying to obtain SSL certificate (%s) from Let's Encrypt %s CA", strings.Join(c.Domains, ","), c.Acme.ApiVersion())

acmeCert, failures := c.Acme.Issue(c.CertificateName, c.Domains)
if len(failures) > 0 {
Expand Down Expand Up @@ -95,14 +102,14 @@ func (c *Context) updateRancherCert(privateKey, cert []byte) {
}
logrus.Infof("Updated Rancher certificate '%s'", c.CertificateName)

err = c.Rancher.UpgradeLoadBalancers(c.RancherCertId)
err = c.Rancher.UpdateLoadBalancers(c.RancherCertId)
if err != nil {
logrus.Fatalf("Failed to upgrade load balancers: %v", err)
}
}

func (c *Context) renew() {
logrus.Infof("Trying to obtain renewed SSL certificate (%s) from Let's Encrypt CA", strings.Join(c.Domains, ","))
logrus.Infof("Trying to obtain renewed SSL certificate (%s) from Let's Encrypt %s CA", strings.Join(c.Domains, ","), c.Acme.ApiVersion())

acmeCert, err := c.Acme.Renew(c.CertificateName)
if err != nil {
Expand All @@ -125,9 +132,9 @@ func (c *Context) timer() <-chan time.Time {

logrus.Infof("Certificate renewal scheduled for %s", next.Format("2006/01/02 15:04 MST"))

// Debug option forces renewal
if c.Debug {
logrus.Debug("Debug mode: Forced certificate renewal in 120 seconds")
// test mode forces renewal
if c.TestMode {
logrus.Debug("Test mode: Forced certificate renewal in 120 seconds")
left = 120 * time.Second
}

Expand Down
12 changes: 6 additions & 6 deletions rancher/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"

"github.com/Sirupsen/logrus"
rancherClient "github.com/rancher/go-rancher/client"
rancherClient "github.com/rancher/go-rancher/v2"
)

// AddCertificate creates a new certificate resource using the given private key and PEM encoded certificate
Expand All @@ -24,7 +24,7 @@ func (r *Client) AddCertificate(name, descr string, privateKey, cert []byte) (*r
return nil, err
}

logrus.Debugf("Waiting for added certificate '%s' to become active", rancherCert.Name)
logrus.Debugf("Waiting for new certificate '%s' to become active", rancherCert.Name)

if err := r.WaitCertificate(rancherCert); err != nil {
return nil, err
Expand Down Expand Up @@ -58,7 +58,7 @@ func (r *Client) UpdateCertificate(certId, descr string, privateKey, cert []byte

// FindCertByName retrieves an existing certificate
func (r *Client) FindCertByName(name string) (*rancherClient.Certificate, error) {
logrus.Debugf("Looking up Rancher certificate by name: '%s'", name)
logrus.Debugf("Looking up Rancher certificate by name: %s", name)

certificates, err := r.client.Certificate.List(&rancherClient.ListOpts{
Filters: map[string]interface{}{
Expand All @@ -75,7 +75,7 @@ func (r *Client) FindCertByName(name string) (*rancherClient.Certificate, error)
return nil, nil
}

logrus.Debugf("Found existing Rancher certificate by name: '%s'", name)
logrus.Debugf("Found existing Rancher certificate by name: %s", name)
return &certificates.Data[0], nil
}

Expand All @@ -87,9 +87,9 @@ func (r *Client) GetCertById(certId string) (*rancherClient.Certificate, error)
}

if rancherCert == nil {
return nil, fmt.Errorf("Rancher certificate with Id '%s' does not exist", certId)
return nil, fmt.Errorf("No such certificate with ID %s", certId)
}

logrus.Debugf("Got Rancher certificate '%s' by Id '%s'", rancherCert.Name, certId)
logrus.Debugf("Got Rancher certificate %s by ID %s", rancherCert.Name, certId)
return rancherCert, nil
}
2 changes: 1 addition & 1 deletion rancher/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package rancher
import (
"time"

rancherClient "github.com/rancher/go-rancher/client"
rancherClient "github.com/rancher/go-rancher/v2"
)

type Client struct {
Expand Down
53 changes: 18 additions & 35 deletions rancher/loadbalancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,44 @@ package rancher

import (
"github.com/Sirupsen/logrus"
rancherClient "github.com/rancher/go-rancher/client"
rancherClient "github.com/rancher/go-rancher/v2"
)

// UpgradeLoadBalancers upgrades all load balancers with the renewed certificate
func (r *Client) UpgradeLoadBalancers(certId string) error {
// UpdateLoadBalancers updates all load balancers with the renewed certificate
func (r *Client) UpdateLoadBalancers(certId string) error {
balancers, err := r.findLoadBalancerServicesByCert(certId)
if err != nil {
return err
}

if len(balancers) == 0 {
logrus.Info("Certificate is not being used by any load balancer")
logrus.Info("Certificate not used by any load balancer")
return nil
}

for _, id := range balancers {
lb, err := r.client.LoadBalancerService.ById(id)
if err != nil {
logrus.Errorf("Failed to get load balancer by id '%s': %v", id, err)
logrus.Errorf("Failed to get load balancer by ID %s: %v", id, err)
continue
}

err = r.upgrade(lb)
err = r.update(lb)
if err != nil {
logrus.Errorf("Failed to upgrade load balancer '%s': %v", lb.Name, err)
logrus.Errorf("Failed to update load balancer '%s': %v", lb.Name, err)
} else {
logrus.Infof("Upgraded load balancer '%s' with renewed certificate", lb.Name)
logrus.Infof("Updated load balancer '%s' with changed certificate", lb.Name)
}
}

return nil
}

func (r *Client) upgrade(lb *rancherClient.LoadBalancerService) error {
upgrade := &rancherClient.ServiceUpgrade{}
upgrade.InServiceStrategy = &rancherClient.InServiceUpgradeStrategy{
LaunchConfig: lb.LaunchConfig,
StartFirst: false,
}
upgrade.ToServiceStrategy = &rancherClient.ToServiceUpgradeStrategy{}
func (r *Client) update(lb *rancherClient.LoadBalancerService) error {

logrus.Debugf("Upgrading load balancer '%s'", lb.Name)
logrus.Debugf("Updating load balancer %s", lb.Name)

service, err := r.client.LoadBalancerService.ActionUpgrade(lb, upgrade)
service, err := r.client.LoadBalancerService.ActionUpdate(lb)
if err != nil {
return err
}
Expand All @@ -55,26 +49,13 @@ func (r *Client) upgrade(lb *rancherClient.LoadBalancerService) error {
logrus.Warnf(err.Error())
}

if service.State == "upgraded" {
logrus.Debugf("Finishing upgrade for load balancer '%s'", lb.Name)

service, err = r.client.Service.ActionFinishupgrade(service)
if err != nil {
return err
}
err = r.WaitService(service)
if err != nil {
logrus.Warnf(err.Error())
}
}

return nil
}

func (r *Client) findLoadBalancerServicesByCert(certId string) ([]string, error) {
var results []string

logrus.Debugf("Looking up load balancers matching certificate id '%s'", certId)
logrus.Debugf("Looking up load balancers matching certificate ID %s", certId)

balancers, err := r.client.LoadBalancerService.List(&rancherClient.ListOpts{
Filters: map[string]interface{}{
Expand All @@ -86,23 +67,25 @@ func (r *Client) findLoadBalancerServicesByCert(certId string) ([]string, error)
return results, err
}
if len(balancers.Data) == 0 {
logrus.Debug("Did not find matching load balancers")
logrus.Debug("Did not find any active load balancers")
return results, nil
}

logrus.Debugf("Found %d active load balancers", len(balancers.Data))

for _, b := range balancers.Data {
if b.DefaultCertificateId == certId {
if b.LbConfig.DefaultCertificateId == certId {
results = append(results, b.Id)
continue
}
for _, id := range b.CertificateIds {
for _, id := range b.LbConfig.CertificateIds {
if id == certId {
results = append(results, b.Id)
break
}
}
}

logrus.Debugf("Found %d matching load balancers", len(results))
logrus.Debugf("Found %d load balancers with matching certificate", len(results))
return results, nil
}
2 changes: 1 addition & 1 deletion rancher/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"fmt"
"time"

rancherClient "github.com/rancher/go-rancher/client"
rancherClient "github.com/rancher/go-rancher/v2"
)

func backoff(maxDuration time.Duration, timeoutMessage string, f func() (bool, error)) error {
Expand Down
24 changes: 24 additions & 0 deletions vendor/github.com/pkg/errors/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions vendor/github.com/pkg/errors/.travis.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions vendor/github.com/pkg/errors/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 987123d

Please sign in to comment.