Beispiel #1
0
def AddSwarmNode(request):
    swarmid = request.GET.get('id')
    ip = request.GET.get('ip')
    port = request.GET.get('port')
    name = request.GET.get('name')

    cursor = connections['default'].cursor()
    sql = "SELECT * FROM swarm where Id=" + swarmid
    print sql
    cursor.execute(sql)
    results = namedtuplefetchall(cursor)

    for row in results:
        id = row.Id
        masterip = row.master
        masterport = row.master_port
        name = row.name
        token = ''
        url = 'http://' + masterip + ':' + masterport
        print sql
        sql = "SELECT * FROM nodes where ip='" + str(masterip)+"' and port='"+str(masterport)+"'"
        print sql
        cursor.execute(sql)
        masterResults = namedtuplefetchall(cursor)
        for rowmaster in masterResults:
            containerid = rowmaster.swarmcontainerid
            attachCont = generalfunctions.funcAttachContainer(url, containerid)
            print attachCont["content"]
            token = attachCont["content"][8:]
            print token

    url = 'http://' + ip + ':' + port
    resp = generalfunctions.funcPullImage(url, 'swarm', '1.1.3')

    if resp["status"] == 'success':
        data = {
            "AttachStdin": False,
            "AttachStdout": True,
            "AttachStderr": True,
            "Tty": False,
            "OpenStdin": False,
            "StdinOnce": False,
            "Cmd": ["join", "--addr=" + ip + ":" + port, "token://" + token],
            "Image": "swarm:1.1.3"
        }
        nodeContainer = generalfunctions.funcCreateContainer(url, name, data)
        if nodeContainer["status"] == 'success':
            nodeContainerId = nodeContainer["id"]
            startCont = generalfunctions.funcStartContainer(url, nodeContainerId)
            if startCont["status"] == 'success':
                print "starting the node success" + ip
                # set master to Y in nodes table
                sql = "UPDATE nodes set ismaster='N',swarmmaster=" + str(id) + ",swarmnodename='" + name + "',swarmcontainerid='" + nodeContainerId + "' where ip='" + ip + "' and port='" + port + "'"
                cursor.execute(sql)
            else:
                print 'starting the container failed' + ip
                return JsonResponse({"status": "failed"})
        else:
            print 'creating the container failed' + ip
            return JsonResponse({"status": "failed"})
    else:
        print 'pulling the image failed' + ip
        return JsonResponse({"status": "failed"})
    return JsonResponse({"status": "success", "content": "Node added to Swarm successfully"})
Beispiel #2
0
def RunContainer(request):
    name = request.GET.get('name')
    image = request.GET.get('image')
    commands = request.GET.get('commands')
    environments = request.GET.get('environments')
    volumes = request.GET.get('volumes')
    #tcpports = request.GET.get('tcpports')
    docker_server_url = request.session['currentip']

    envs=[]
    last = len(environments.split(',')) - 1
    i=0

    if commands != "":
        commands = commands.split(",")
    else:
        commands = None

    if environments!="":
        for env in environments.split(','):
            envs.append(env)
    else:
        envs = None

    if volumes!="":
        volumes = volumes.split(",")
    else:
        volumes=None

    jsonport=[]
    # if tcpports!="":
    #     ports=tcpports.split(",")
    #     for port in ports:
    #         port=port.split(":")
    #         portarray = {"PrivatePort": int(port[1]), "PublicPort": int(port[0]), "Type": "tcp"}
    #         jsonport.append(portarray)
    # else:
    #     tcpports=[]
    #
    # print jsonport
    vols=[]
    #for volume in volumes:
    #    volume = volume.split(':')
    #    vols.append(volume[0]+":"+volume[1])

    #print vols

    headers = {'Content-Type': 'application/json'}
    data={
          "AttachStdin": False,
          "AttachStdout": True,
          "AttachStderr": True,
          "Tty": False,
          "OpenStdin": False,
          "StdinOnce": False,
          "Cmd": commands,
          "Env": envs,
          "Image": image,
          "HostConfig": {"Binds": volumes},
          "Ports": jsonport
        }
    #,"HostConfig":{"Binds": volumes}
    print json.dumps(data)

    r = generalfunctions.funcCreateContainer(docker_server_url, name, data)

    return JsonResponse(r)
Beispiel #3
0
def HandleSwarm(request):
    response = '{"master":[{"ip": "153.92.34.6", "port":"2375", "name":"master1"}],"node":[{"ip": "153.92.35.46", "port":"2375", "name":"node1"}]}'
    print 'here'
    print 'Raw Data: "%s"' % request.body
    jsonrequest = json.loads(request.body)
    print jsonrequest
    token = ''
    swarmmaster=0

    #check master connectivity
    for master in jsonrequest["master"]:
        print master["ip"]
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((master["ip"], int(master["port"])))
        if result == 0:
            print "Port is open"
        else:
            print "Port is not open"
            return JsonResponse({'status': 'failed', 'content': 'Please check the IP and port('+master["ip"] + ":" + master["port"]+')'})


    #check nodes connectivity
    for node in jsonrequest["node"]:
        print node["ip"]
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((node["ip"], int(node["port"])))
        if result == 0:
            print "Port is open"
        else:
            print "Port is not open"
            return JsonResponse({'status': 'failed', 'content': 'Please check the IP and port('+node["ip"] + ":" + node["port"]+')'})

    #create master node
    for master in jsonrequest["master"]:
        ip = master["ip"]
        port = master["port"]
        name = master["name"]
        url = 'http://'+master["ip"] + ':' + master["port"]
        resp = generalfunctions.funcPullImage(url, 'swarm', '1.1.3')
        if resp["status"] == 'success':
            data={
              "AttachStdin": False,
              "AttachStdout": True,
              "AttachStderr": True,
              "Tty": False,
              "OpenStdin": False,
              "StdinOnce": False,
              "Cmd": ["create"],
              "Image": "swarm:1.1.3"
            }
            masterContainer = generalfunctions.funcCreateContainer(url, name, data)
            if masterContainer["status"] == 'success':
                print 'container created successfully'
                masterContainerId = masterContainer["id"]
                print 'master id:' + masterContainerId
                startCont = generalfunctions.funcStartContainer(url, masterContainerId)
                if startCont["status"] == 'success':
                    print 'container started successfully'
                    attachCont = generalfunctions.funcAttachContainer(url, masterContainerId)
                    print attachCont["content"]
                    token = attachCont["content"][8:]
                    print token
                    #insert the master into database
                    cursor = connections['default'].cursor()
                    sql="INSERT into swarm(name, master, master_port) VALUES('"+name+"','"+ip+"','"+port+"')"
                    cursor.execute(sql)
                    swarmmaster=cursor.lastrowid

                    #set master to Y in nodes table
                    sql="UPDATE nodes set ismaster='Y', swarmmaster=0, swarmcontainerid='"+masterContainerId+"',swarmnodename='"+name+"' where ip='"+ip+"' and port='"+port+"'"
                    cursor.execute(sql)
                else:
                    print 'starting the container failed'
            else:
                print 'creating the container failed'
        else:
            print 'pulling the image failed'




    #create slave nodes
    for node in jsonrequest["node"]:
        ip = node["ip"]
        port = node["port"]
        name = node["name"]
        url = 'http://'+ ip + ':' + port
        resp = generalfunctions.funcPullImage(url, 'swarm', '1.1.3')

        if resp["status"] == 'success':
            data={
              "AttachStdin": False,
              "AttachStdout": True,
              "AttachStderr": True,
              "Tty": False,
              "OpenStdin": False,
              "StdinOnce": False,
              "Cmd": ["join", "--addr="+ip+":"+port, "token://"+token],
              "Image": "swarm:1.1.3"
            }
            nodeContainer = generalfunctions.funcCreateContainer(url, name, data)
            if nodeContainer["status"] == 'success':
                nodeContainerId = nodeContainer["id"]
                startCont = generalfunctions.funcStartContainer(url, nodeContainerId)
                if startCont["status"] == 'success':
                    print "starting the node success" + ip
                    #set master to Y in nodes table
                    sql="UPDATE nodes set ismaster='N',swarmmaster="+str(swarmmaster)+",swarmnodename='"+name+"',swarmcontainerid='"+nodeContainerId+"' where ip='"+ip+"' and port='"+port+"'"
                    cursor.execute(sql)
                else:
                    print 'starting the container failed' + ip
                    return JsonResponse({"status": "failed"})
            else:
                print 'creating the container failed' + ip
                return JsonResponse({"status": "failed"})
        else:
            print 'pulling the image failed' + ip
            return JsonResponse({"status": "failed"})


    #create swarm master manager
    for master in jsonrequest["master"]:
        ip = master["ip"]
        port = master["port"]
        name = master["name"] + 'manage'
        url = 'http://'+master["ip"] + ':' + master["port"]

        resp = generalfunctions.funcPullImage(url, 'swarm', '1.1.3')
        if resp["status"] == 'success':
            data={
              "PortBindings": { "2375/tcp": [{ "HostPort": "5001" }] },
              "AttachStdin": False,
              "AttachStdout": True,
              "AttachStderr": True,
              "Tty": False,
              "OpenStdin": False,
              "StdinOnce": False,
              "Cmd": ["manage", "token://"+token],
              "Image": "swarm:1.1.3"
            }
            masterManagerContainer = generalfunctions.funcCreateContainer(url, name, data)
            if masterManagerContainer["status"] == 'success':
                masterManagerContainerId = masterManagerContainer["id"]
                startCont = generalfunctions.funcStartContainer(url, masterManagerContainerId)
                if startCont["status"] == 'success':
                    print 'master manager started'
                    sql="INSERT into nodes(ip, port, name, ismaster, swarmmaster, swarmnodename, swarmcontainerid) values('"+ip+"','5001', '"+name+"', 'N', 0, '"+name+"', '"+masterManagerContainerId+"')"
                    cursor.execute(sql)
                else:
                    print 'starting the container failed'
                    return JsonResponse({"status": "failed"})
            else:
                print 'creating the container failed'
                return JsonResponse({"status": "failed"})
        else:
            print 'pulling the image failed' + ip
            return JsonResponse({"status": "failed"})



    return JsonResponse({"status": "success", "content": "Swarm created successfully"})
Beispiel #4
0
def RunContainer(request):
    name = request.GET.get('name')
    image = request.GET.get('image')
    commands = request.GET.get('commands')
    environments = request.GET.get('environments')
    volumes = request.GET.get('volumes')
    portBindings = request.GET.get("portBindings")
    strportBindings = portBindings
    docker_server_url = request.session['currentip']

    envs=[]
    last = len(environments.split(',')) - 1
    i=0

    if commands != "":
        commands = commands.split(",")
    else:
        commands = None

    if environments!="":
        for env in environments.split(','):
            envs.append(env)
    else:
        envs = None

    if volumes!="":
        volumes = volumes.split(",")
    else:
        volumes=None

    exposedPortsObj = {}
    if portBindings!="":
        portBindings = portBindings.split(",")
        for portBinding in portBindings:
            portBinding= portBinding.split(":")
            if len(portBinding) == 2:
                if portBinding[0] == '' or portBinding[1] == '':
                    return JsonResponse({"status": "failure", "content": "Port binding in wrong format. Correct format: HOST_PORT:CONTAINER_PORT"})
                else:
                    index = portBinding[1]+'/tcp'
                    exposedPortsObj[index]={}
            else:
                return JsonResponse({"status": "failure", "content": "Invalid Port binding."})
    else:
        portBindings=None

    headers = {'Content-Type': 'application/json'}
    data={
          "AttachStdin": False,
          "AttachStdout": True,
          "AttachStderr": True,
          "Tty": False,
          "OpenStdin": False,
          "StdinOnce": False,
          "Cmd": commands,
          "Env": envs,
          "Image": image,
          "HostConfig": {"Binds": volumes},
          "ExposedPorts": exposedPortsObj
        }

    print json.dumps(data)

    r = generalfunctions.funcCreateContainer(docker_server_url, name, data)
    if r["status"] == "success":
        generalfunctions.funcAddPortsToDB(r["id"], str(strportBindings))

    return JsonResponse(r)