我想到的一個選擇是定期檢查連接的節點,併爲每個節點創建一個具有適當數量副本的服務。它可能不是一個非常優雅的解決方案,但至少可以與以下Python腳本一起使用。
#!/usr/bin/env python3
import docker
def rescale(service_prefix,service_arguments):
client = docker.from_env()
service_names = [s.name for s in client.services.list()]
for node in client.nodes.list():
# Only handle ready nodes
if node.attrs['Status']['State'] != 'ready':
continue
service_name = service_prefix+node.id
if service_name not in service_names:
# Service does not exist -> Create it
cpus = node.attrs['Description']['Resources']['NanoCPUs']/1000000000
print("Creating service %s with %i replicas"%(service_name,cpus))
mode={'Replicated':{'Replicas':int(cpus)}}
constraints=['node.id==%s'%node.id]
client.services.create(name=service_name, mode=mode, constraints=constraints, **service_arguments)
else:
# Continue running this service
service_names.remove(service_name)
# Remove services of no longer existing nodes
for service in service_names:
print("Removing service %s"%service)
client.services.get(service).remove()
rescale(service_prefix="evaluation_",
service_arguments={'image':'imagename','networks':['swarmnet']})