Skip to content

Commit

Permalink
Merge pull request #22 from OpenCHAMI/fix-minor-issues
Browse files Browse the repository at this point in the history
Fix minor issues
  • Loading branch information
davidallendj authored Nov 15, 2024
2 parents a55ecf2 + f0c48d5 commit 5b351d2
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 51 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
**.conf
**.ignore
**.tar.gz
dist/
4 changes: 1 addition & 3 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ builds:
- amd64
- arm64
flags:
- -tags:all
- -tags=all
archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of uname.
Expand All @@ -27,7 +27,6 @@ archives:
- LICENSE
- CHANGELOG.md
- README.md
- lib/
dockers:
-
image_templates:
Expand All @@ -45,7 +44,6 @@ dockers:
- LICENSE
- CHANGELOG.md
- README.md
- lib/
checksum:
name_template: 'checksums.txt'
snapshot:
Expand Down
4 changes: 1 addition & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,13 @@ FROM cgr.dev/chainguard/wolfi-base

RUN apk add --no-cache tini bash
RUN mkdir -p /configurator
RUN mkdir -p /configurator/lib

# nobody 65534:65534
USER 65534:65534

# copy the binary and all of the default plugins
COPY configurator /configurator/configurator
COPY lib/* /configurator/lib/*

CMD ["/configurator"]
CMD ["/configurator/configurator"]

ENTRYPOINT [ "/sbin/tini", "--" ]
2 changes: 0 additions & 2 deletions cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ var (
tokenFetchRetries int
templatePaths []string
pluginPath string
cacertPath string
useCompression bool
)

Expand Down Expand Up @@ -175,7 +174,6 @@ func init() {
generateCmd.Flags().StringSliceVar(&templatePaths, "template", []string{}, "set the paths for the Jinja 2 templates to use")
generateCmd.Flags().StringVar(&pluginPath, "plugin", "", "set the generator plugin path")
generateCmd.Flags().StringVarP(&outputPath, "output", "o", "", "set the output path for config targets")
generateCmd.Flags().StringVar(&cacertPath, "cacert", "", "path to CA cert. (defaults to system CAs)")
generateCmd.Flags().IntVar(&tokenFetchRetries, "fetch-retries", 5, "set the number of retries to fetch an access token")
generateCmd.Flags().StringVar(&remoteHost, "host", "http://localhost", "set the remote host")
generateCmd.Flags().IntVar(&remotePort, "port", 80, "set the remote port")
Expand Down
14 changes: 11 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import (

configurator "github.com/OpenCHAMI/configurator/pkg"
"github.com/OpenCHAMI/configurator/pkg/util"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)

var (
configPath string
config configurator.Config
configPath string
cacertPath string
verbose bool
targets []string
outputPath string
Expand Down Expand Up @@ -40,11 +42,13 @@ func Execute() {

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "./config.yaml", "set the config path")
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "set the config path")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "set to enable verbose output")
rootCmd.PersistentFlags().StringVar(&cacertPath, "cacert", "", "path to CA cert. (defaults to system CAs)")
}

func initConfig() {
// empty from not being set
if configPath != "" {
exists, err := util.PathExists(configPath)
if err != nil {
Expand All @@ -53,9 +57,13 @@ func initConfig() {
} else if exists {
config = configurator.LoadConfig(configPath)
} else {
config = configurator.NewConfig()
// show error and exit since a path was specified
log.Error().Str("path", configPath).Msg("config file not found")
os.Exit(1)
}
} else {
// set to the default value and create a new one
configPath = "./config.yaml"
config = configurator.NewConfig()
}

Expand Down
10 changes: 5 additions & 5 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ var serveCmd = &cobra.Command{
fmt.Printf("%v\n", string(b))
}

// set up the routes and start the server
// set up the routes and start the serve
server := server.Server{
Config: &config,
Server: &http.Server{
Expand All @@ -55,15 +55,15 @@ var serveCmd = &cobra.Command{
Retries: config.Server.Jwks.Retries,
},
GeneratorParams: generator.Params{
Args: args,
PluginPath: pluginPath,
Args: args,
// PluginPath: pluginPath,
// Target: target, // NOTE: targets are set via HTTP requests (ex: curl http://configurator:3334/generate?target=dnsmasq)
Verbose: verbose,
},
}

// start listening with the server
err := server.Serve()
err := server.Serve(cacertPath)
if errors.Is(err, http.ErrServerClosed) {
if verbose {
fmt.Printf("Server closed.")
Expand All @@ -78,7 +78,7 @@ var serveCmd = &cobra.Command{
func init() {
serveCmd.Flags().StringVar(&config.Server.Host, "host", config.Server.Host, "set the server host")
serveCmd.Flags().IntVar(&config.Server.Port, "port", config.Server.Port, "set the server port")
serveCmd.Flags().StringVar(&pluginPath, "plugin", "", "set the generator plugins directory path")
// serveCmd.Flags().StringVar(&pluginPath, "plugin", "", "set the generator plugins directory path")
serveCmd.Flags().StringVar(&config.Server.Jwks.Uri, "jwks-uri", config.Server.Jwks.Uri, "set the JWKS url to fetch public key")
serveCmd.Flags().IntVar(&config.Server.Jwks.Retries, "jwks-fetch-retries", config.Server.Jwks.Retries, "set the JWKS fetch retry count")
rootCmd.AddCommand(serveCmd)
Expand Down
20 changes: 15 additions & 5 deletions pkg/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/OpenCHAMI/configurator/pkg/util"
"github.com/nikolalohinski/gonja/v2"
"github.com/nikolalohinski/gonja/v2/exec"
"github.com/rs/zerolog/log"
)

type (
Expand All @@ -35,6 +36,7 @@ type (
TemplatePaths []string
PluginPath string
Target string
Client *configurator.SmdClient
Verbose bool
}
)
Expand Down Expand Up @@ -408,17 +410,24 @@ func Generate(config *configurator.Config, params Params) (FileMap, error) {
func GenerateWithTarget(config *configurator.Config, params Params) (FileMap, error) {
// load generator plugins to generate configs or to print
var (
client configurator.SmdClient
target configurator.Target
generator Generator
err error
ok bool
)

// check if we have a client from params first and create new one if not
if params.Client == nil {
client = configurator.NewSmdClient(
configurator.WithHost(config.SmdClient.Host),
configurator.WithPort(config.SmdClient.Port),
configurator.WithAccessToken(config.AccessToken),
configurator.WithCertPoolFile(config.CertPath),
)
target configurator.Target
generator Generator
err error
ok bool
)
} else {
client = *params.Client
}

// check if a target is supplied
if len(params.Args) == 0 && params.Target == "" {
Expand All @@ -440,6 +449,7 @@ func GenerateWithTarget(config *configurator.Config, params Params) (FileMap, er
generator, ok = DefaultGenerators[params.Target]
if !ok {
// only load the plugin needed for this target if we don't find default
log.Error().Msg("did not find target in default generators")
generator, err = LoadPlugin(target.PluginPath)
if err != nil {
return nil, fmt.Errorf("failed to load plugin: %w", err)
Expand Down
87 changes: 57 additions & 30 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
package server

import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"time"
Expand Down Expand Up @@ -60,13 +63,33 @@ func New(config *configurator.Config) *Server {
}

// Main function to start up configurator as a service.
func (s *Server) Serve() error {
func (s *Server) Serve(cacertPath string) error {
// create client just for the server to use to fetch data from SMD
_ = &configurator.SmdClient{
client := &configurator.SmdClient{
Host: s.Config.SmdClient.Host,
Port: s.Config.SmdClient.Port,
}

// add cert to client if `--cacert` flag is passed
if cacertPath != "" {
cacert, _ := os.ReadFile(cacertPath)
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(cacert)
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
InsecureSkipVerify: true,
},
DisableKeepAlives: true,
Dial: (&net.Dialer{
Timeout: 120 * time.Second,
KeepAlive: 120 * time.Second,
}).Dial,
TLSHandshakeTimeout: 120 * time.Second,
ResponseHeaderTimeout: 120 * time.Second,
}
}

// set the server address with config values
s.Server.Addr = fmt.Sprintf("%s:%d", s.Config.Server.Host, s.Config.Server.Port)

Expand All @@ -76,7 +99,7 @@ func (s *Server) Serve() error {
var err error
tokenAuth, err = configurator.FetchPublicKeyFromURL(s.Config.Server.Jwks.Uri)
if err != nil {
logrus.Errorf("failed to fetch JWKS: %w", err)
logrus.Errorf("failed to fetch JWKS: %v", err)
continue
}
break
Expand Down Expand Up @@ -104,12 +127,12 @@ func (s *Server) Serve() error {
)

// protected routes if using auth
r.HandleFunc("/generate", s.Generate)
r.HandleFunc("/generate", s.Generate(client))
r.HandleFunc("/templates", s.ManageTemplates)
})
} else {
// public routes without auth
router.HandleFunc("/generate", s.Generate)
router.HandleFunc("/generate", s.Generate(client))
router.HandleFunc("/templates", s.ManageTemplates)
}

Expand All @@ -127,32 +150,36 @@ func (s *Server) Close() {
// This is the corresponding service function to generate templated files, that
// works similarly to the CLI variant. This function takes similiar arguments as
// query parameters that are included in the HTTP request URL.
func (s *Server) Generate(w http.ResponseWriter, r *http.Request) {
// get all of the expect query URL params and validate
s.GeneratorParams.Target = r.URL.Query().Get("target")
if s.GeneratorParams.Target == "" {
writeErrorResponse(w, "must specify a target")
return
}
func (s *Server) Generate(client *configurator.SmdClient) func(w http.ResponseWriter, r *http.Request) {

return func(w http.ResponseWriter, r *http.Request) {
// get all of the expect query URL params and validate
s.GeneratorParams.Target = r.URL.Query().Get("target")
s.GeneratorParams.Client = client
if s.GeneratorParams.Target == "" {
writeErrorResponse(w, "must specify a target")
return
}

// generate a new config file from supplied params
outputs, err := generator.GenerateWithTarget(s.Config, s.GeneratorParams)
if err != nil {
writeErrorResponse(w, "failed to generate file: %w", err)
return
}
// generate a new config file from supplied params
outputs, err := generator.GenerateWithTarget(s.Config, s.GeneratorParams)
if err != nil {
writeErrorResponse(w, "failed to generate file: %v", err)
return
}

// marshal output to JSON then send response to client
tmp := generator.ConvertContentsToString(outputs)
b, err := json.Marshal(tmp)
if err != nil {
writeErrorResponse(w, "failed to marshal output: %w", err)
return
}
_, err = w.Write(b)
if err != nil {
writeErrorResponse(w, "failed to write response: %w", err)
return
// marshal output to JSON then send response to client
tmp := generator.ConvertContentsToString(outputs)
b, err := json.Marshal(tmp)
if err != nil {
writeErrorResponse(w, "failed to marshal output: %v", err)
return
}
_, err = w.Write(b)
if err != nil {
writeErrorResponse(w, "failed to write response: %v", err)
return
}
}
}

Expand All @@ -163,7 +190,7 @@ func (s *Server) Generate(w http.ResponseWriter, r *http.Request) {
func (s *Server) ManageTemplates(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("this is not implemented yet"))
if err != nil {
writeErrorResponse(w, "failed to write response: %w", err)
writeErrorResponse(w, "failed to write response: %v", err)
return
}
}
Expand Down
File renamed without changes.

0 comments on commit 5b351d2

Please sign in to comment.