swirl/biz/docker/docker.go

69 lines
1.2 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 (
apiVersion = "1.32"
)
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
}
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 {
2017-10-27 12:31:30 +00:00
if misc.Options.DockerEndpoint == "" {
os.Setenv("DOCKER_API_VERSION", apiVersion)
2017-09-26 12:50:09 +00:00
m.client, err = client.NewEnvClient()
} else {
2017-10-27 12:31:30 +00:00
m.client, err = client.NewClient(misc.Options.DockerEndpoint, apiVersion, nil, nil)
2017-09-26 12:50:09 +00:00
}
if err != nil {
return
}
}
}
return context.TODO(), m.client, nil
}
func (m *manager) Logger() *log.Logger {
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}
}