netbird/relay/cmd/main.go

91 lines
2.1 KiB
Go
Raw Normal View History

2024-05-17 20:24:06 +02:00
package main
import (
2024-07-01 11:50:18 +02:00
"crypto/tls"
"fmt"
2024-05-17 20:24:06 +02:00
"os"
2024-05-27 09:42:27 +02:00
"os/signal"
"syscall"
2024-05-23 13:24:02 +02:00
2024-05-17 20:24:06 +02:00
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
2024-05-17 20:24:06 +02:00
2024-07-01 11:50:18 +02:00
"github.com/netbirdio/netbird/encryption"
2024-05-17 20:24:06 +02:00
"github.com/netbirdio/netbird/relay/server"
2024-05-27 09:42:27 +02:00
"github.com/netbirdio/netbird/util"
2024-05-17 20:24:06 +02:00
)
var (
2024-07-01 11:50:18 +02:00
listenAddress string
letsencryptDataDir string
letsencryptDomain string
rootCmd = &cobra.Command{
Use: "relay",
Short: "Relay service",
Long: "Relay service for Netbird agents",
Run: execute,
}
)
2024-05-17 20:24:06 +02:00
func init() {
_ = util.InitLog("trace", "console")
rootCmd.PersistentFlags().StringVarP(&listenAddress, "listen-address", "l", ":1235", "listen address")
2024-07-01 11:50:18 +02:00
rootCmd.PersistentFlags().StringVarP(&letsencryptDataDir, "letsencrypt-data-dir", "d", "", "a directory to store Let's Encrypt data. Required if Let's Encrypt is enabled.")
rootCmd.PersistentFlags().StringVarP(&letsencryptDomain, "letsencrypt-domain", "a", "", "a domain to issue Let's Encrypt certificate for. Enables TLS using Let's Encrypt. Will fetch and renew certificate, and run the server with TLS")
2024-05-17 20:24:06 +02:00
}
2024-05-27 09:42:27 +02:00
func waitForExitSignal() {
osSigs := make(chan os.Signal, 1)
signal.Notify(osSigs, syscall.SIGINT, syscall.SIGTERM)
2024-06-25 15:13:08 +02:00
<-osSigs
2024-05-27 09:42:27 +02:00
}
2024-05-17 20:24:06 +02:00
func execute(cmd *cobra.Command, args []string) {
2024-07-01 11:50:18 +02:00
srvCfg := server.Config{
Address: listenAddress,
}
if hasLetsEncrypt() {
tlscfg, err := setupTLS()
if err != nil {
log.Errorf("%s", err)
os.Exit(1)
}
srvCfg.TLSConfig = tlscfg
}
2024-05-17 20:24:06 +02:00
srv := server.NewServer()
2024-07-01 11:50:18 +02:00
err := srv.Listen(srvCfg)
2024-05-17 20:24:06 +02:00
if err != nil {
log.Errorf("failed to bind server: %s", err)
os.Exit(1)
}
2024-05-26 22:14:33 +02:00
2024-05-27 09:42:27 +02:00
waitForExitSignal()
err = srv.Close()
if err != nil {
log.Errorf("failed to close server: %s", err)
os.Exit(1)
}
2024-05-17 20:24:06 +02:00
}
2024-07-01 11:50:18 +02:00
func hasLetsEncrypt() bool {
return letsencryptDataDir != "" && letsencryptDomain != ""
}
func setupTLS() (*tls.Config, error) {
certManager, err := encryption.CreateCertManager(letsencryptDataDir, letsencryptDomain)
if err != nil {
return nil, fmt.Errorf("failed creating LetsEncrypt cert manager: %v", err)
}
return certManager.TLSConfig(), nil
}
func main() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}