Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add signal handler for SIGHUP to reload the HTTP and NATS servers #117

Open
github-actions bot opened this issue Feb 17, 2025 · 0 comments
Open

add signal handler for SIGHUP to reload the HTTP and NATS servers #117

github-actions bot opened this issue Feb 17, 2025 · 0 comments
Assignees
Labels

Comments

@github-actions
Copy link
Contributor

// TODO: add signal handler for SIGHUP to reload the HTTP and NATS servers

		log.Fatalf("Error closing key.pem: %v", err)
	}
	log.Debug("wrote key.pem")
	if config.NoRotateCerts {
		log.Debug("Not rotating certs, as per config")
		return
	}
	go rotateTLSCerts()
}

func rotateTLSCerts() {
	log.Debug("Rotating TLS certificates...")
	CertFile := config.CertFile
	// open the cert file and determine the notbefore date and the notafter date
	// if the notafter date is within 33% of the config.CertificateValidTime, then
	// generate a new cert
	// otherwise sleep for 1 day and check again
	needsRotation := func() (bool, error) {
		file, err := os.Open(CertFile)
		if err != nil {
			return false, errors.Join(err, errors.New("could not open cert file"))
		}
		defer file.Close()
		stats, statsErr := file.Stat()
		if statsErr != nil {
			return false, errors.Join(statsErr, errors.New("could not stat cert file"))
		}
		size := stats.Size()
		bytes := make([]byte, size)
		bufr := bufio.NewReader(file)
		_, err = bufr.Read(bytes)
		if err != nil {
			return false, errors.Join(err, errors.New("could not read cert file into buffer"))
		}
		block, _ := pem.Decode(bytes)
		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return false, errors.Join(err, errors.New("could not parse cert"))
		}
		return time.Now().After(cert.NotAfter.Add(-config.CertificateValidTime / 3)), nil
	}
	reloadHttpServer := func() {
		shutdownTimeout, cancel := context.WithTimeout(context.Background(), 15*time.Second)
		defer cancel()
		httpServer.Shutdown(shutdownTimeout)
		SetHttpServer(server.StartAPIServer())
	}
	for {
		shouldRotate, err := needsRotation()
		if err != nil {
			log.Error(err)
			time.Sleep(time.Minute)
			continue
		}
		if shouldRotate {
			genCert(true)
			pki.ReloadNatsServer()
			reloadHttpServer()
			// TODO: add signal handler for SIGHUP to reload the HTTP and NATS servers
		}
		time.Sleep(24 * time.Hour)
	}
}

func SetHttpServer(s *http.Server) {
	httpServer = s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant