def RestartContainer(IP, port, container): print "-------------restart---container %s " % container dockerc = Dockerapi(IP, port) dockerc.RestartContainer(container) result = {'resultInfo': u'重启容器成功!!', 'type': 'restart'} print "ssssssssssssssssss" return {'result': result}
def GetDockerImages(): DockerServerList = DockerHost.objects.filter(enabled=1) for server in DockerServerList: try: docker=Dockerapi(server.hostip,server.port) DockerImagesdata=docker.AllImages() except: return u"Connect Docker host is Error!!!" else: for image in DockerImagesdata: if image['RepoTags'][0] == '<none>:<none>': continue imageid=image['Id'].split(':')[-1] for repo in image['RepoTags']: if Dockerimage.objects.filter(repository=repo): Oldimage = Dockerimage.objects.get(repository=repo) Oldimage.repository = repo Oldimage.imagesId=imageid Oldimage.tag = repo.split(':')[-1] Oldimage.imagehost = server.hostip Oldimage.size = image['Size'] Oldimage.save() else: Newimage=Dockerimage(imagesId=imageid, repository=repo, tag = repo.split(':')[-1], imagehost = server.hostip, size=image['Size'], ) Newimage.save() return "Get all imgeas is oK!!"
def Logout(request): #记录用户登出时间 #history_login = History_Login.objects.filter(user=request.user).order_by('-id')[0] #history_login.save() #停止用户的容器 if request.session.get('user_id'): try: containerinfo = DockerContainer.objects.filter( status='running').values("image", "Name", 'hostip') DockerContainerCount2 = DockerContainer.objects.filter( status='running') print("Docker_running="), DockerContainerCount2 for it in containerinfo: hostip = it['hostip'] dockerinfo = DockerHost.objects.filter(hostip=hostip).values( "hostip", "port") docker_port = dockerinfo[0]['port'] Container_name = it['Name'] image = it['image'] if Container_name == image + '-' + str( request.session['user_id']): print("Container_name="), Container_name docker_Instance = Dockerapi(hostip, docker_port) stop = docker_Instance.killContainer(Container_name) else: continue except: pass #登出用户 logout(request) #删除用户的session if request.session.get('user_name'): del request.session['user_name'] return HttpResponseRedirect('/', )
def getsocket(request, containerId): if request.is_websocket: request.websocket.send('Welcome to Simpletour DevOps!!') IP = DockerContainer.objects.get(containerID=containerId).hostip PORT = DockerHost.objects.get(hostip=IP).port docker_api = Dockerapi(IP, PORT) try: container = docker_api.dockerConnect.exec_create( container=containerId, cmd="/bin/bash", user='******', tty=True, stdout=True, stderr=True, stdin=True, ) a = docker_api.dockerConnect.exec_start(container['Id'], stream=True, tty=True, detach=False, socket=True) docker_api.dockerConnect.exec_resize(container['Id'], height=40, width=80) for message in request.websocket: if not message: break a.send(message.encode('utf-8')) request.websocket.send(a.recv(65535)) except: request.websocket.send('主机无法连接!!')
def DockerImageDelete(request, imageid): username = request.session.get('user_name') if request.method == 'GET': Image = Dockerimage.objects.get(id=imageid) if Image: repo = Image.repository #查询DOCKER主机IP及端口 ip = Image.imagehost port = DockerHost.objects.get(hostip=ip).port dockerapi = Dockerapi(ip, port) a = dockerapi.DeleteImages(repo) Image.delete() Operation.objects.create(Opuser=username, Opaction=u'删除Docker镜像 %s' % repo) return HttpResponse(a) else: return HttpResponse(u"没有该镜像!!")
def GetDockerServerinfo(): DockerServerList = DockerHost.objects.filter(enabled=1) for server in DockerServerList: try: docker=Dockerapi(server.hostip,server.port) Dockerdata=docker.GetallContainers() for container in Dockerdata: '''获取容器最新状态进行修改''' if DockerContainer.objects.filter(containerID=container['Id']): status=container['Status'] if 'Up' in status: status= 'running' else: status = 'Exited' OldContainer = DockerContainer.objects.get(containerID=container['Id']) OldContainer.Name=container['Names'][0].lstrip('/') OldContainer.command=container['Command'] OldContainer.status=status OldContainer.image=container['Image'] OldContainer.hostip=server.hostip OldContainer.Created=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(container['Created'])) OldContainer.save() else: '''如果没有容器就添加''' status = container['Status'] if 'Up' in status: status = 'running' else: status = 'Exited' NewContainer=DockerContainer(containerID=container['Id'], Name=container['Names'][0].lstrip('/'), command=container['Command'], status=status, image=container['Image'], hostip=server.hostip, Created=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(container['Created']))) NewContainer.save() except: print "sssssss" return u"Connect Docker host is Error!!!" return u"OK"
def experDetail(request): usersession = request.session.get('user_id') user_name = request.session.get('user_name') if request.method == 'GET': experid = request.GET.get('id') moduleid = request.GET.get('module') experdetail = Experinfo.objects.filter( experid=experid).values("reserved1") try: imageinfo = Sysinfo.objects.filter(sysid=moduleid).values( "imagehost", "repository", "index_port") imageinfo = list(imageinfo) index_port = imageinfo[0]['index_port'] imagehost = imageinfo[0]['imagehost'] repository = imageinfo[0]['repository'].split(':')[0] dockerinfo = DockerHost.objects.filter(hostip=imagehost).values( "hostip", "port") docker_port = dockerinfo[0]['port'] container_port = int(index_port) + int(usersession) Container_name = repository + '-' + str(usersession) docker_Instance = Dockerapi(imagehost, docker_port) start = docker_Instance.StartContainer(Container_name) url = "http://" + imagehost + ':' + str(container_port) ret = { 'usersession': usersession, 'experdetail': experdetail, 'url': url } return render(request, 'teachmanager/exper_info_detail.html', ret) except: ret = {'usersession': usersession, 'experdetail': experdetail} return render(request, 'teachmanager/exper_info_detail.html', ret) else: experid = request.POST.get('id') experinfo = Experinfo.objects.filter(experid=experid).values( "experid", "name", "introduction", "duration", "parent_id", "detail") experinfo = list(experinfo) ret = {'experinfo': experinfo} return HttpResponse(json.dumps(ret), content_type="application/json")
def DockerLogOutput(request, containerid): usersession = request.session.get('user_id') if request.method == 'GET': IP = DockerContainer.objects.get(containerID=containerid).hostip port = DockerHost.objects.get(hostip=IP).port try: dockerserver = Dockerapi(IP, port) data = dockerserver.LogContainer(containerid, tail=30) data = data.split('\n') except docker.errors.NotFound: return HttpResponse('没有该容器') ret = { 'usersession': usersession, 'dockerlogsdata': data, 'containerid': containerid } return render(request, 'dockermanager/dockerhosts_logs.html', ret) else: IP = DockerContainer.objects.get(containerID=containerid).hostip port = DockerHost.objects.get(hostip=IP).port try: dockerserver = Dockerapi(IP, port) data = dockerserver.LogContainer(containerid, tail=30) data = data.split('\n') except docker.errors.NotFound: return HttpResponse('没有该容器') ret = {'dockerlogsdata': data} return HttpResponse(json.dumps(ret))
def DeleteContainer(IP, port, container): print "-------------delete---container %s " % container dockerc = Dockerapi(IP, port) dockerc.removeContainer(container, v=False, force=True) result = {'resultInfo': u'容器删除成功!!', 'type': 'delete'} return {'result': result}
def StartContainer(IP, port, container): print "|------------start------container------------|" dockerc = Dockerapi(IP, port) data = dockerc.StartContainer(container) result = {'resultInfo': u'容器启动成功!!', 'type': 'start'} return {'result': result}
def StopContainer(docker): print "-------------stop------container-----" dockerc = Dockerapi(docker['host'], docker['port']) data = dockerc.StopContainer(docker['container']) result = {'resultInfo': u'容器停止成功!!', 'type': 'stop'} return {'result': result}