sshpoke/internal/config/model.go

104 lines
2.5 KiB
Go
Raw Normal View History

2023-11-16 20:09:40 +03:00
package config
import (
"net/http"
"path/filepath"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
)
2023-11-17 20:39:00 +03:00
var Default Config
2023-11-16 20:09:40 +03:00
type Config struct {
2023-11-17 20:39:00 +03:00
Debug bool `mapstructure:"debug"`
PluginAPIPort int `mapstructure:"plugin_api_port" validate:"gte=0,lte=65535"`
Docker DockerConfig `mapstructure:"docker"`
DefaultServer string `mapstructure:"default_server"`
Servers []Server `mapstructure:"servers"`
2023-11-16 20:09:40 +03:00
}
type DockerConfig struct {
2023-11-17 20:39:00 +03:00
FromEnv *bool `mapstructure:"from_env,omitempty"`
2023-11-16 20:09:40 +03:00
CertPath string `mapstructure:"cert_path"`
TLSVerify *bool `mapstructure:"tls_verify,omitempty"`
Host string `mapstructure:"host"`
Version string `mapstructure:"version"`
}
2023-11-17 20:39:00 +03:00
type DriverParams map[string]interface{}
type DriverType string
const (
DriverSSH DriverType = "ssh"
DriverPlugin DriverType = "plugin"
DriverNull DriverType = "null"
)
type Server struct {
Name string `mapstructure:"name" validate:"required"`
Driver DriverType `mapstructure:"driver"`
Params DriverParams `mapstructure:"params"`
}
2023-11-16 20:09:40 +03:00
func (d DockerConfig) Opts(c *client.Client) error {
2023-11-17 20:39:00 +03:00
if d.FromEnv == nil || *d.FromEnv {
2023-11-16 20:09:40 +03:00
return client.FromEnv(c)
}
ops := []client.Opt{
d.withTLSClientConfig(),
d.withHost(),
d.withVersion(),
}
for _, op := range ops {
if err := op(c); err != nil {
return err
}
}
return nil
}
func (d DockerConfig) withTLSClientConfig() client.Opt {
return func(c *client.Client) error {
dockerCertPath := d.CertPath
if dockerCertPath == "" {
return nil
}
skipTLSVerify := false
if d.TLSVerify != nil && !(*d.TLSVerify) {
skipTLSVerify = true
}
options := tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
InsecureSkipVerify: skipTLSVerify,
}
tlsConfig, err := tlsconfig.Client(options)
if err != nil {
return err
}
return client.WithHTTPClient(&http.Client{
Transport: &http.Transport{TLSClientConfig: tlsConfig},
CheckRedirect: client.CheckRedirect,
})(c)
}
}
func (d DockerConfig) withHost() client.Opt {
return func(c *client.Client) error {
if host := d.Host; host != "" {
return client.WithHost(host)(c)
}
return nil
}
}
func (d DockerConfig) withVersion() client.Opt {
return func(c *client.Client) error {
return client.WithVersion(d.Version)(c)
}
}