随机一个ip检测是否可用
import random
def get_available_ip(request):
ipBase = '10.10.0.'
while true:
num = random.randint(2,254)
ip = ipBase + str(num)
if subprocess.call(["ping", "-c", "2", ip]) != 0: # 只发送两个ECHO_REQUEST包
return HttpResponse(json.dumps(({"ip": ip})))
#print("{0} is alive.".format(ip))
return None
连接到本地创建容器
def create_staticip_docker(request):
if request.method == "GET":
new_ip = request.GET.get('ip')
image = request.GET.get('image')
images = docker_img.objects.get(img_name=image)
user = UserProfile.objects.get(username='admin')
node = docker_node.objects.get(ip='127.0.0.1')
base_url = 'tcp://' + node.ip + ':2375' #连接到本地
client = docker.DockerClient(base_url=base_url, version='auto', timeout=10)
images_name = images.img_name
command = images.command
#设置容器名称
docker_name_base = user.username
docker_num = container.objects.all().count() + 1
docker_name = docker_name_base + str(docker_num)
#容器归到static网络中
assign_network = 'static'
#建立并开启容器
new_docker = client.containers.run(images_name, detach=True, tty=True, stdin_open=True, name=docker_name,command=command)
dockernet = client.networks.get(assign_network)
dockernet.connect(new_docker, ipv4_address=new_ip)
bridgenet = client.networks.get('bridge')
bridgenet.disconnect(new_docker)
new_container = client.containers.get(docker_name)
ip_addr = new_container.attrs['NetworkSettings']['Networks']['static']['IPAddress']
print(ip_addr)
mydocker = container.objects.create(Only_Id=new_docker.id,name=docker_name,user=user,cpu_cores=1,memory=1,img=images,region=node.belong,node=node,portmap=None)
mydocker.save()
return HttpResponse(json.dumps(({"ip": ip_addr})))