sshpoke/internal/config/model.go

104 lines
2.5 KiB
Go

package config
import (
"net/http"
"path/filepath"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
)
var Default Config
type Config struct {
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"`
}
type DockerConfig struct {
FromEnv *bool `mapstructure:"from_env,omitempty"`
CertPath string `mapstructure:"cert_path"`
TLSVerify *bool `mapstructure:"tls_verify,omitempty"`
Host string `mapstructure:"host"`
Version string `mapstructure:"version"`
}
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"`
}
func (d DockerConfig) Opts(c *client.Client) error {
if d.FromEnv == nil || *d.FromEnv {
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)
}
}