Docker Swarm代码分析笔记(6)——swarm driver的NewCluster函数

Swarm driverNewCluster函数的核心功能如下(cluster/swarm/cluster.go):

discoveryCh, errCh := cluster.discovery.Watch(nil)
go cluster.monitorDiscovery(discoveryCh, errCh)
go cluster.monitorPendingEngines()

cluster.discovery.Watch的定义如下:

Watch(stopCh <-chan struct{}) (<-chan Entries, <-chan error)

返回两个channel:第一个channel类型是Entriestype Entries []*Entry),用来传输cluster所包含的主机信息,第二个channel用来通知是否有错误发生。

Cluster.monitorDiscovery功能是整理Cluster.engines

select {
    case entries := <-ch:
        added, removed := currentEntries.Diff(entries)
        currentEntries = entries

        // Remove engines first. `addEngine` will refuse to add an engine
        // if there's already an engine with the same ID.  If an engine
        // changes address, we have to first remove it then add it back.
        for _, entry := range removed {
            c.removeEngine(entry.String())
        }

        for _, entry := range added {
            c.addEngine(entry.String())
        }
    case err := <-errCh:
        log.Errorf("Discovery error: %v", err)
    }

Cluster.monitorPendingEngines则是验证处于pending状态的Cluster.engines现在是否能够连接上:

for _, e := range pEngines {
        if e.TimeToValidate() {
            go c.validatePendingEngine(e)
        }
    }

 

Docker Swarm代码分析笔记(5)——cluster/cluster.go

cluster\cluster.go文件定义了Cluster interface

// Cluster is exported
type Cluster interface {
    // Create a container
    CreateContainer(config *ContainerConfig, name string, authConfig *types.AuthConfig) (*Container, error)

    // Remove a container
    RemoveContainer(container *Container, force, volumes bool) error

    // Return all images
    Images() Images
    ......
}

目前实现了mesoscluster/mesos/cluster.go,目前仍然处于试验阶段)和swarmcluster/swarm/cluster.go)两种driver。如果你想实现自己的driver,就要实现上面Cluster interface的所有函数。