swirl/biz/docker/docker.go

73 lines
1.4 KiB
Go
Raw Normal View History

2017-09-26 12:50:09 +00:00
package docker
import (
"context"
"os"
2017-09-26 12:50:09 +00:00
"sync"
"github.com/cuigh/auxo/log"
"github.com/cuigh/swirl/misc"
"github.com/docker/docker/api/types/swarm"
2017-09-26 12:50:09 +00:00
"github.com/docker/docker/client"
)
const (
defaultAPIVersion = "1.32"
2017-09-26 12:50:09 +00:00
)
2017-10-27 12:31:30 +00:00
var mgr = &manager{}
2017-09-26 12:50:09 +00:00
type manager struct {
client *client.Client
locker sync.Mutex
logger log.Logger
2017-09-26 12:50:09 +00:00
}
func (m *manager) Do(fn func(ctx context.Context, cli *client.Client) error) (err error) {
ctx, cli, err := m.Client()
if err != nil {
return err
}
return fn(ctx, cli)
}
func (m *manager) Client() (ctx context.Context, cli *client.Client, err error) {
if m.client == nil {
m.locker.Lock()
defer m.locker.Unlock()
if m.client == nil {
apiVersion := misc.Options.DockerAPIVersion
if apiVersion == "" {
apiVersion = defaultAPIVersion
}
2017-10-27 12:31:30 +00:00
if misc.Options.DockerEndpoint == "" {
os.Setenv("DOCKER_API_VERSION", apiVersion)
m.client, err = client.NewClientWithOpts(client.FromEnv)
2017-09-26 12:50:09 +00:00
} else {
m.client, err = client.NewClientWithOpts(client.WithHost(misc.Options.DockerEndpoint), client.WithVersion(apiVersion))
2017-09-26 12:50:09 +00:00
}
if err != nil {
return
}
}
}
return context.TODO(), m.client, nil
}
func (m *manager) Logger() log.Logger {
2017-09-26 12:50:09 +00:00
if m.logger == nil {
m.locker.Lock()
defer m.locker.Unlock()
if m.logger == nil {
m.logger = log.Get("docker")
}
}
return m.logger
}
func version(v uint64) swarm.Version {
return swarm.Version{Index: v}
}