func main() {

	fmt.Println("dockerapi started...")
	time.Sleep(time.Millisecond * 5000)
	fmt.Println("action: " + ACTION)
	fmt.Println("containers: " + CONTAINERS)
	var containers = strings.Split(CONTAINERS, ",")
	var docker *dockerapi.Client
	var err error
	docker, err = dockerapi.NewClient(DOCKER_HOST)
	if err != nil {
		fmt.Println(err.Error())
	}
	err = docker.Ping()

	for i := range containers {
		fmt.Println(ACTION + " issued for " + containers[i])
		switch ACTION {
		case "stop":
			err = docker.StopContainer(containers[i], 5)
		case "start":
			err = docker.StartContainer(containers[i], nil)
		default:
			fmt.Println(ACTION + " unsupported action")
		}
		if err != nil {
			fmt.Println(err.Error())
		}
		time.Sleep(time.Millisecond * 2000)
	}
}
func main() {
	logger = log.New(os.Stdout, "logger: ", log.Lshortfile|log.Ldate|log.Ltime)
	var VERSION = os.Getenv("CCP_VERSION")

	logger.Println("dnsbridgeserver " + VERSION + ": starting")

	getEnvVars()

	var dockerConnected = false
	var tries = 0
	var docker *dockerapi.Client
	var err error
	for tries = 0; tries < MAX_TRIES; tries++ {
		docker, err = dockerapi.NewClient(DOCKER_URL)
		err = docker.Ping()
		if err != nil {
			logger.Println("could not ping docker host")
			logger.Println("sleeping and will retry in %d sec\n", delaySeconds)
			time.Sleep(delay)
		} else {
			logger.Println("no err in connecting to docker")
			dockerConnected = true
			break
		}
	}

	if dockerConnected == false {
		logger.Println("failing, could not connect to docker after retries")
		panic("cant connect to docker")
	}

	events := make(chan *dockerapi.APIEvents)
	assert(docker.AddEventListener(events))
	logger.Println("dnsbridgeserver: Listening for Docker events...")
	for msg := range events {
		switch msg.Status {
		//case "start", "create":
		case "start":
			logger.Println("event: " + msg.Status + " ID=" + msg.ID + " From:" + msg.From)
			dnsbridgeapi.Action(logger, msg.Status, msg.ID, docker, TTL, CONSUL_URL, DOMAIN)
		case "stop":
			logger.Println("event: " + msg.Status + " ID=" + msg.ID + " From:" + msg.From)
			dnsbridgeapi.Action(logger, msg.Status, msg.ID, docker, TTL, CONSUL_URL, DOMAIN)
		case "destroy":
			logger.Println("event: " + msg.Status + " ID=" + msg.ID + " From:" + msg.From)
			dnsbridgeapi.Action(logger, msg.Status, msg.ID, docker, TTL, CONSUL_URL, DOMAIN)
		case "die":
			logger.Println("event: " + msg.Status + " ID=" + msg.ID + " From:" + msg.From)
		default:
			logger.Println("event: " + msg.Status)
		}
	}

}
Esempio n. 3
0
func (p *DockerInDockerPool) clientInit(client *dockerapi.Client) error {
	if len(p.preloadImages) == 0 {
		return client.Ping()
	}

	for _, imageData := range p.preloadImages {
		err := client.LoadImage(dockerapi.LoadImageOptions{
			InputStream: bytes.NewReader(imageData),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 4
0
// Docker generates a docker client
func Docker() (client *Client, err error) {
	var c *api.Client
	if misc.ZeroOrNil(current.CertPath) {
		c, err = api.NewClient(current.Endpoint)
	} else {
		cert := fmt.Sprintf("%s/cert.pem", current.CertPath) // X.509 Certificate
		key := fmt.Sprintf("%s/key.pem", current.CertPath)   // Private Key
		ca := fmt.Sprintf("%s/ca.pem", current.CertPath)     // Certificate authority
		c, err = api.NewTLSClient(current.Endpoint, cert, key, ca)
	}
	if !misc.ZeroOrNil(c) {
		err = c.Ping()
	}
	if misc.ZeroOrNil(err) {
		c.SkipServerVersionCheck = true
		return &Client{c, current}, nil
	}
	return nil, err
}
Esempio n. 5
0
// dockerEventListener читает из канала события от докера и реагирует на них
func dockerEventListener(server *SSHServer, client *docker.Client, events chan *docker.APIEvents) {
	for {
		select {
		case event, ok := <-events:
			if !ok {
				log.Printf("Docker daemon connection interrupted")
				break
			}

			// Если был запущен контейнер, проверяем что у него есть 22 порт и добавляем
			if event.Status == "start" {
				log.Printf("Container %s was started", event.ID[:12])

				container, _ := client.InspectContainer(event.ID)
				if len(container.NetworkSettings.Ports) == 0 {
					continue
				}
				for port, mapping := range container.NetworkSettings.Ports {
					if port == "22/tcp" {
						log.Printf("Added %v: %s:%v\n", container.ID[:12], mapping[0].HostIP, mapping[0].HostPort)
						server.AddHost(container.ID, fmt.Sprintf("%s:%v", mapping[0].HostIP, mapping[0].HostPort))
					}
				}
			}

			// Если контейнер был удалён/убит, убераем его
			if event.Status == "stop" || event.Status == "die" {
				log.Printf("Container %s was removed", event.ID[:12])

				server.RemoveContainer(event.ID)
			}

		case <-time.After(10 * time.Second):
			if err := client.Ping(); err != nil {
				log.Printf("Unable to ping docker daemon: %s", err)
			}
		}
	}
}
Esempio n. 6
0
// NewClient returns a new docker client or an error
func NewClient(dcfg Config) (Client, error) {
	var client *docker.Client
	var err error
	if dcfg.Endpoint != "" {
		client, err = docker.NewClient(dcfg.Endpoint)
	} else if dcfg.UseBoot2Docker {
		endpoint := os.Getenv("DOCKER_HOST")
		if endpoint != "" {
			path := os.Getenv("DOCKER_CERT_PATH")
			cert := fmt.Sprintf("%s/cert.pem", path)
			key := fmt.Sprintf("%s/key.pem", path)
			ca := fmt.Sprintf("%s/ca.pem", path)
			client, err = docker.NewTLSClient(endpoint, cert, key, ca)
		}
	} else {
		return Client{}, errors.New("empty docker configuration")
	}
	if err != nil || client == nil {
		return Client{dcfg, client}, err
	}

	return Client{dcfg, client}, client.Ping()
}
Esempio n. 7
0
func generateFromEvents(client *docker.Client, configs ConfigFile) {
	configs = configs.filterWatches()
	if len(configs.Config) == 0 {
		return
	}

	wg.Add(1)
	defer wg.Done()

	for {
		if client == nil {
			var err error
			endpoint, err := getEndpoint()
			if err != nil {
				log.Printf("Bad endpoint: %s", err)
				time.Sleep(10 * time.Second)
				continue
			}

			client, err = NewDockerClient(endpoint)
			if err != nil {
				log.Printf("Unable to connect to docker daemon: %s", err)
				time.Sleep(10 * time.Second)
				continue
			}
			generateFromContainers(client)
		}

		eventChan := make(chan *docker.APIEvents, 100)
		defer close(eventChan)

		watching := false
		for {

			if client == nil {
				break
			}
			err := client.Ping()
			if err != nil {
				log.Printf("Unable to ping docker daemon: %s", err)
				if watching {
					client.RemoveEventListener(eventChan)
					watching = false
					client = nil
				}
				time.Sleep(10 * time.Second)
				break

			}

			if !watching {
				err = client.AddEventListener(eventChan)
				if err != nil && err != docker.ErrListenerAlreadyExists {
					log.Printf("Error registering docker event listener: %s", err)
					time.Sleep(10 * time.Second)
					continue
				}
				watching = true
				log.Println("Watching docker events")
			}

			select {

			case event := <-eventChan:
				if event == nil {
					if watching {
						client.RemoveEventListener(eventChan)
						watching = false
						client = nil
					}
					break
				}

				if event.Status == "start" || event.Status == "stop" || event.Status == "die" {
					log.Printf("Received event %s for container %s", event.Status, event.ID[:12])
					generateFromContainers(client)
				}
			case <-time.After(10 * time.Second):
				// check for docker liveness
			}

		}
	}
}