예제 #1
0
파일: views.py 프로젝트: fengbb/hcdocker
def resetpassword(request):
    msg = ""
    path = request.get_full_path()
    # print(path)
    containerid = path.split("/")[3][:12]
    # print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except:
        msg = "数据库查询有问题"
    dockername = container.containername
    # print(dockername)
    dockerip = container.dockerhost
    # print(dockerip)
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    # print(dockerpassword)
    chagepassword = rundockercmd.resetpassword(rundockercmd.sshClient(dockerip, dockerpassword), dockername)
    print(chagepassword)
    if chagepassword:
        Container.objects.filter(containerid__startswith=containerid).update(password=chagepassword)
        msg = "重置密码成功"
    else:
        msg = "重置密码错误"
    return HttpResponseRedirect("/containers/list/?p1=%s" % (msg))
예제 #2
0
파일: views.py 프로젝트: fengbb/hcdocker
def containerrestart(request):
    msg = ""
    path = request.get_full_path()
    # print(path)
    containerid = path.split("/")[3][:12]
    # print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except:
        msg = "数据库查询有问题"
    # print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    # print(dockerpassword)
    containerip = container.containerhost
    password = container.password
    # print(containerip)
    # print(dockerip,containerip,password)
    restartresult = rundockercmd.restartContainer(
        rundockercmd.sshClient(dockerip, dockerpassword),
        dockerid=containerid,
        containerip=containerip,
        password=password,
    )
    if restartresult:
        msg = "容器重启成功"
    else:
        msg = "容器重启失败"
    # print(restartresult)
    # print(msg)
    # return render_to_response('containerslist.html',{'msg':msg})
    return HttpResponseRedirect("/containers/list/?p1=%s" % (msg))
예제 #3
0
파일: views.py 프로젝트: sc-yuns/docker
def containercommit(request):
    msg = ''
    path = request.get_full_path()
    #print(path)
    containerid = path.split('/')[3][:12]
    #print(containerid)
    commitimagename = request.POST.get('commitimagename')
    print(commitimagename)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except :
        msg = '数据库查询有问题'
    print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    print(dockerpassword)
    commitresult = rundockercmd.commitContainer(rundockercmd.sshClient(dockerip,dockerpassword),containerid,commitimagename)
    msg = 'commit 失败' + commitresult
    if commitresult:
        #print(commitresult)
        tagresult = rundockercmd.pushImage(rundockercmd.sshClient(dockerip,dockerpassword),commitresult,commitimagename)
        print(tagresult)
        msg = '提交远程完成!'
    else:
        return render_to_response('containercommit.html',{'commitresult':commitresult})
    return render_to_response('containercommit.html',{'msg':msg})
예제 #4
0
def containerrestart(request):
    msg = ''
    path = request.get_full_path()
    #print(path)
    containerid = path.split('/')[3][:12]
    #print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except :
        msg = '数据库查询有问题'
    #print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    #print(dockerpassword)
    containerip = container.containerhost
    password = container.password
    #print(dockerip,containerip,password)
    restartresult = rundockercmd.restartContainer(rundockercmd.sshClient(dockerip,dockerpassword),dockerid=containerid,containerip=containerip,password=password)
    if restartresult:
        msg = '容器重启成功'
    else:
        msg = '容器重启失败'
    #print(restartresult)
    return render_to_response('containerslist.html',{'msg':msg})
예제 #5
0
def containerdelete(request):
    path = request.get_full_path()
    #print(path)
    containerid = path.split('/')[3][:12]
    #print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except :
        msg = '数据库查询有问题'
    #print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    containerip = container.containerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    #print(dockerpassword)
    deleteresult = rundockercmd.deleteContainer(rundockercmd.sshClient(dockerip,dockerpassword),containerid)
    print(deleteresult)
    if deleteresult:
        return render_to_response('containerslist.html',{'deleteresult':deleteresult })
    else:
        try:
            container = Container.objects.get(containerid__startswith=containerid).delete()
            ContainerIp.objects.filter(ip=containerip).update(used=0)
            #container = Container.objects.filter(containerid=containerid).delete()
        except :
            msg = '删除数据失败'
            #print(msg)
    return HttpResponseRedirect('/containers/list/')
예제 #6
0
파일: duo_auth.py 프로젝트: hhauer/myinfo
 def _wrapped_view(request, *args, **kwargs):
     if duo_authenticated(request):
         return view_func(request, *args, **kwargs)
     path = urlquote(request.get_full_path())
     return HttpResponseRedirect(
         '%s?%s=%s' % (
             settings.DUO_LOGIN_URL, redirect_field_name, path))
예제 #7
0
파일: views.py 프로젝트: fengbb/hcdocker
def containercommit(request):
    username = request.session.get("username")
    msg = ""
    departmentobj = Project.objects.all()
    # print(departmentobj)
    if request.method == "POST":
        path = request.get_full_path()
        # print(path)
        containerid = path.split("/")[3][:12]
        # print(containerid)
        commitimagename = request.POST.get("commitimagename")
        # print(commitimagename)
        commitdeparment = request.POST.get("department")
        print(commitdeparment)
        commitbz = request.POST.get("bz")
        print(commitbz)
        imageexist = ImageName.objects.filter(imagename=commitimagename)  # 判断容器名是否存在
        if imageexist:
            msg = "容器名已存在!!!"
        else:
            try:
                container = Container.objects.get(containerid__startswith=containerid)
            except:
                msg = "数据库查询有问题"
            # print(container.password,container.containername,container.containerhost,container.dockerhost)
            dockerip = container.dockerhost  # 获取docker主机IP地址
            docker = DockerHost.objects.get(ip=dockerip)  # 根据ip地址查询
            dockerpassword = docker.hostpassword  # 获取密码
            # print(dockerpassword)
            commitresult = rundockercmd.commitContainer(
                rundockercmd.sshClient(dockerip, dockerpassword), containerid, commitimagename
            )
            msg = "commit 失败" + commitresult
            if commitresult:
                registryup = registryjson.getregistryjson(registryjson.sshClient(dockerip, dockerpassword))
                m = re.findall(r"repositories", registryup)
                if m:
                    print(commitresult)
                    tagresult = rundockercmd.pushImage(
                        rundockercmd.sshClient(dockerip, dockerpassword), commitresult, commitimagename
                    )
                    print(tagresult)
                    msg = "提交远程镜像完成!"
                    createimage = ImageName.objects.create(
                        username=username, imagename=commitimagename, departmentname=commitdeparment, bz=commitbz
                    )
                else:
                    msg = "私有仓库有问题,请联管理员"
                return render_to_response("containercommit.html", {"msg": msg})
                # return HttpResponseRedirect('/containers/list/?p1=%s' % (msg))
            else:
                print(commitresult)
                return render_to_response("containercommit.html", {"commitresult": commitresult, "msg": msg})
            return render_to_response("containercommit.html", {"msg": msg})
        return render_to_response("containercommit.html", {"msg": msg})
        # return HttpResponseRedirect('/containers/list/?p1=%s' % (msg))
    return render_to_response(
        "containercommit.html", {"msg": msg, "departmentobj": departmentobj, "username": username}
    )
예제 #8
0
def getInterfaceList(request):
    navActiveStatusDic={'home':'','mock':'','more':'','help':'','links':'','dataCount':''}
    if 'home' in request.get_full_path():
        navActiveStatusDic['home'] ='active'
        navActiveStatusDic['mock'] =''  
    else:
        navActiveStatusDic['mock'] ='active'
        navActiveStatusDic['home'] =''  
        
    if 'Protocol' in request.get_full_path() :
            protocolGet=request.GET['Protocol']
            interfaceNameGet=request.GET['InterfaceName']
            interfaceListResult=interface.objects.filter(protocol=protocolGet).filter(interfaceName__icontains=interfaceNameGet)
            return render(request,'getInterfaceList.html',{'interfaceListResult':interfaceListResult,'navActiveStatusDic':navActiveStatusDic})

    else:
        return render(request,'getInterfaceList.html',{'navActiveStatusDic':navActiveStatusDic})   
예제 #9
0
def events_by_cat(request):
    '''
    This view in particular makes calls to search API of EventBrite and retrieves the list of events
    that are based on user's choice of categories and it also appends page number in url, keeping in minde pagination
    We make sure to use exception handling in case of invalid input
    '''
    try:
        response=urllib.request.urlopen('https://www.eventbriteapi.com/v3/events/search/?categories={}&token={}&page={}'
                .format(request.GET['categories'],token,request.GET['page']))
    except Exception as e:
        return HttpResponse(str(e))

    #If no exception occurs, we read reponse and put it in events_list in json format
    with response as f:
        event_list = loads(f.read().decode('utf-8'))
    events_in_cat=[]

    '''These variables are used to send in context of iframecontent.html template in anchor tag
    to help generate url for particular pages of the event list'''

    page_count=event_list["pagination"]["page_count"] #gets total page count from JSON data
    page_number=event_list["pagination"]["page_number"] #gets current page count from JSON data


    for event in event_list["events"]:
        events_in_cat.append(event_class(event['name']['text'],event['url']))


    #if page number is equal to total number of pages, we go back to page 0
    if page_number==page_count:
        next_page_number=1
    else:
    #else we add 1 to page number
        next_page_number=page_number+1

    template = loader.get_template('eventbriteAPI/ifamecontent.html')
    context = {
        'events':events_in_cat,
        'page_number':page_number,
        'page_count':page_count,
        'previous':request.get_full_path().split('page')[0]+'page='+str(page_number-1),
        'next':request.get_full_path().split('page')[0]+'page='+str(next_page_number),
    }

    return HttpResponse(template.render(context, request))
예제 #10
0
def runService(request):
    returnMessage=''
    navActiveStatusDic={'home':'','mock':'active','more':'','help':''}        
    if 'runServices' in request.get_full_path():
        protocolGet=request.GET['runProtocol']
        mode=request.GET['Mode']
        returnMessage=RunCMD(protocolGet,mode)
        return render(request,'runservice.html',{'returnMessage':returnMessage,'navActiveStatusDic':navActiveStatusDic})
    else:
        return render(request,'runservice.html',{'returnMessage':returnMessage,'navActiveStatusDic':navActiveStatusDic})
예제 #11
0
def containercommit(request):
    username = request.session.get('username')
    msg = ''
    departmentobj = Project.objects.all()
    #print(departmentobj)
    if request.method == "POST":
        path = request.get_full_path()
        #print(path)
        containerid = path.split('/')[3][:12]
        #print(containerid)
        commitimagename = request.POST.get('commitimagename')
        #print(commitimagename)
        commitdeparment = request.POST.get('department')
        print(commitdeparment)
        commitbz = request.POST.get('bz')
        print(commitbz)
        imageexist = ImageName.objects.filter(imagename=commitimagename) #判断容器名是否存在
        if imageexist:
              msg = "容器名已存在!!!"
        else:
            try:
                container = Container.objects.get(containerid__startswith=containerid)
            except :
                msg = '数据库查询有问题'
            #print(container.password,container.containername,container.containerhost,container.dockerhost)
            dockerip = container.dockerhost #获取docker主机IP地址
            docker = DockerHost.objects.get(ip=dockerip) #根据ip地址查询
            dockerpassword = docker.hostpassword #获取密码
            #print(dockerpassword)

            commitresult = rundockercmd.commitContainer(rundockercmd.sshClient(dockerip,dockerpassword),containerid,commitimagename)
            msg = 'commit 失败' + commitresult
            if commitresult:
                registryup = registryjson.getregistryjson(registryjson.sshClient(dockerip,dockerpassword))
                m = re.findall(r"repositories",registryup)
                if m:
                    print(commitresult)
                    tagresult = rundockercmd.pushImage(rundockercmd.sshClient(dockerip,dockerpassword),commitresult,commitimagename)
                    print(tagresult)
                    msg = '提交远程完成!'
                    createimage = ImageName.objects.create(username=username,imagename=commitimagename,departmentname=commitdeparment,bz=commitbz)
                else:
                    msg ='私有仓库有问题,请联管理员'
                return render_to_response('containercommit.html',{'msg':msg})
            else:
                return render_to_response('containercommit.html',{'commitresult':commitresult,'msg':msg})
            return render_to_response('containercommit.html',{'msg':msg})
        return render_to_response('containercommit.html',{'msg':msg})
    return render_to_response('containercommit.html',{'msg':msg,'departmentobj':departmentobj,'username':username})
예제 #12
0
def containerstop(request):
    path = request.get_full_path()
    #print(path)
    containerid = path.split('/')[3][:12]
    #print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except :
        msg = '数据库查询有问题'
    #print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    #print(dockerpassword)
    stopresult = rundockercmd.stopContainer(rundockercmd.sshClient(dockerip,dockerpassword),containerid)
    #print(stopresult)
    return HttpResponseRedirect('/containers/list/')
예제 #13
0
파일: views.py 프로젝트: fengbb/hcdocker
def containerdelete(request):
    msg = ""
    path = request.get_full_path()
    # print(path)
    containerid = path.split("/")[3][:12]
    # print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except:
        msg = "数据库查询有问题"
    # print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost  # 查询docker主机ip
    containerip = container.containerhost  # 查询容器ip
    cpun = container.cpunumber  # 查询使用cpu号
    print(cpun)
    formatobj = Format.objects.filter(ip__ip=dockerip).filter(usedcpu=cpun)  # 查找对应主机上对应模板是否存在
    print(formatobj)
    for fcpu in formatobj:
        sumc = fcpu.cnumber  # 查询现在运行了多少台容器
        print(sumc)
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    # print(dockerpassword)
    deleteresult = rundockercmd.deleteContainer(rundockercmd.sshClient(dockerip, dockerpassword), containerid)
    print(deleteresult)
    if deleteresult:
        msg = "删除失败,失败原因:" + deleteresult
    else:
        try:
            container = Container.objects.get(containerid__startswith=containerid).delete()  # 删除数据库
            ContainerIp.objects.filter(ip=containerip).update(used=0)
            if sumc == 6:
                print("使用达到6个cpu")
                Format.objects.filter(ip__ip=dockerip).filter(usedcpu=cpun).update(cnumber=sumc - 1)
                Format.objects.filter(ip__ip=dockerip).filter(usedcpu=cpun).filter(ifexit=1).update(ifexit=0)
                msg = "删除容器成功"
            else:
                print("使用没有达到6个cpu")
                Format.objects.filter(ip__ip=dockerip).filter(usedcpu=cpun).update(cnumber=sumc - 1)
                msg = "删除容器成功"
            # container = Container.objects.filter(containerid=containerid).delete()
        except:
            msg = "数据库查询有问题"
            # print(msg)
    return HttpResponseRedirect("/containers/list/?p1=%s" % (msg))
예제 #14
0
파일: views.py 프로젝트: fengbb/hcdocker
def containerstop(request):
    msg = ""
    path = request.get_full_path()
    containerid = path.split("/")[3][:12]
    # print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except:
        msg = "数据库查询有问题"
    # print(container.password,container.containername,container.containerhost,container.dockerhost)
    dockerip = container.dockerhost
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    # print(dockerpassword)
    stopresult = rundockercmd.stopContainer(rundockercmd.sshClient(dockerip, dockerpassword), containerid)
    if stopresult:
        msg = "关闭容器成功"
    else:
        msg = "关闭容器失败"
    return HttpResponseRedirect("/containers/list/?p1=%s" % (msg))
예제 #15
0
def getSignPackage(request):
    # 获得jsapi_ticket
    jsapiTicket = getJsApiTicket()

    # 注意 URL 一定要动态获取,不能 hardcode.
    # 获取当前页面的url
    url = 'http://' + request.get_host() + request.get_full_path()

    # 获取timestamp(时间戳)
    timestamp = int(time.time())
    # 获取noncestr(随机字符串)
    nonceStr = createNonceStr()

    # 这里参数的顺序要按照 key 值 ASCII 码升序排序
    # 得到signature
    # $signature = hashlib.sha1(string).hexdigest();
    ret = {
        'nonceStr': nonceStr,
        'jsapi_ticket': jsapiTicket,
        'timestamp': timestamp,
        'url': url
    }

    string = '&'.join(['%s=%s' % (key.lower(), ret[key]) for key in sorted(ret)])
    # signature = hashlib.sha1(string).hexdigest()
    sha1 = hashlib.sha1()
    sha1.update(string.encode('utf-8'))
    signature = sha1.hexdigest()

    signPackage = {
        "appId": 'wx8bc079dad4b03645',
        "nonceStr": nonceStr,
        "timestamp": timestamp,
        "url": url,
        "signature": signature,
        "rawString": string
    }
    return signPackage;
예제 #16
0
def resetpassword(request):
    path = request.get_full_path()
    #print(path)
    containerid = path.split('/')[3][:12]
    #print(containerid)
    try:
        container = Container.objects.get(containerid__startswith=containerid)
    except :
        msg = '数据库查询有问题'
    dockername = container.containername
    print(dockername)
    dockerip = container.dockerhost
    print(dockerip)
    docker = DockerHost.objects.get(ip=dockerip)
    dockerpassword = docker.hostpassword
    print(dockerpassword)
    chagepassword = rundockercmd.resetpassword(rundockercmd.sshClient(dockerip,dockerpassword),dockername)
    print(chagepassword)
    if chagepassword:
        Container.objects.filter(containerid__startswith=containerid).update(password=chagepassword)
    else:
        msg = '重置密码错误'
    return HttpResponseRedirect('/containers/list/')
예제 #17
0
def configPage(request):
    navActiveStatusDic={'home':'','mock':'','more':'','help':'','links':'','dataCount':''}
    submitMessage=''
    display='alert alert-success hidden'
#     print (timezone.now())
#     print (datetime.datetime.strptime(datetime.timezone(),'YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]')) 
    if request.method=='POST' and 'uploadResponseFile' in request.get_full_path():
        file_Obj=request.FILES.get('uploadResponseFile',None)
        submitMessage=handle_uploaded_file(file_Obj)
        display='alert alert-warning show'
        navActiveStatusDic['mock'] ='active'          
        return render(request,'index.html',{'submitMessageDic':submitMessage,'display':display,'navActiveStatusDic':navActiveStatusDic},context_instance=RequestContext(request))
    elif request.method == 'POST':
            protocol=request.POST.get('Protocol')
            interfaceName=str(request.POST.get('InterfaceName')).strip()
            businessName=str(request.POST.get('BusinessName')).strip()
            mockConfig=request.POST.get('ConfigParameter')
            try:
                result=interface.objects.get_or_create(protocol=protocol,interfaceName=interfaceName,businessName=businessName,mockConfig=mockConfig,operator='sysem',isvalid=True)
                if result[1] == False:
                    submitMessage=' record has already exist '
                    display='alert alert-info show'
                else:
                    saveResponseFile(interfaceName,mockConfig)
                    WriteAPIJson(interfaceName)
                    submitMessage=' add successfully,please remeber to upload your response data file '
                    display='alert alert-success show'

            except:
                submitMessage='interface '+interfaceName+' has already exist1'
                display='alert alert-warning show'
            navActiveStatusDic['mock'] ='active'          
            return render(request,'index.html',{'submitMessageDic':submitMessage,'display':display,'navActiveStatusDic':navActiveStatusDic},context_instance=RequestContext(request))
    else:
            navActiveStatusDic['mock'] ='active' 
            return render(request,'index.html',{'submitMessageDic':submitMessage,'display':display,'navActiveStatusDic':navActiveStatusDic},context_instance=RequestContext(request))
예제 #18
0
def delete_metadata(request):
    """
    Delete the metadata for the DOI.

    Args:
        request (HTTPRequest): The HTTP request

    Return:
        a HTTPResponse

    """
    _doi = get_doi_from_request(request, "metadata")
    LOGGING.info("Delete metadata doi: %s", _doi)
    url = urljoin(DATACITE_URL, request.get_full_path())
    try:
        doi_suffix = _doi.split(DOI_PREFIX, 1)[1]
    except IndexError:
        return get_response(
            "Bad Request - wrong prefix, doi should start "
            "with %s" % DOI_PREFIX, 400)

    if not is_authorized(request, doi_suffix):
        return get_response("Unauthorized - insufficient privileges", 403)
    return _delete(url)
예제 #19
0
파일: views.py 프로젝트: hoangxtr/_CNPM
def result(request):
    # hanle response json from momo
    url = request.get_full_path()
    query = urlsplit(url).query
    query = urllib.parse.parse_qs(query)
    query = json.dumps(query)
    query = str(json.loads(query)['errorCode'])
    query = query.replace("['", '')
    query = query.replace("']", '')

    # Change status of Order after paying
    username = str(request.user)
    user = User.objects.filter(username=username)
    user = Customer.objects.get(user=user[0])

    order, created = Order.objects.get_or_create(customer=user, status=0)
    if query == '0':  # Having successful payment
        order.status = 1
    else:
        order.status = 0

    #  return result for customer
    context = {'result': query}
    return render(request, '_CNPM/resultPayment.html', context)
예제 #20
0
def redirect_to_login(request):
    from django.conf import settings
    login_url = settings.LOGIN_URL
    path = urlquote(request.get_full_path())
    tup = login_url, REDIRECT_FIELD_NAME, path
    return HttpResponseRedirect('%s?%s=%s' % tup)
예제 #21
0
def ChartView(request):
    SetCountryList()
    return render(request, 'helloworld/chart.html',
                  {"url": request.get_full_path()})
예제 #22
0
def TableView(request):
    SetCountryList()
    return render(request, 'helloworld/home.html',
                  {"url": request.get_full_path()})
예제 #23
0
def ForbiddenResponse(request, errormsg=None, exception=None):
    error = mark_safe("You do not have permission to access this resource.")
    if not request.user.is_authenticated:
        login_url = settings.LOGIN_URL + '?' + urllib.parse.urlencode({'next': request.get_full_path()})
        error += mark_safe(' You are <strong>not logged in</strong>, so maybe <a href="%s">logging in</a> would help.' % (login_url))
    return HttpError(request, status=403, title="Forbidden", error=error, errormsg=errormsg)
예제 #24
0
def status(request):
    currentURL = request.build_absolute_uri(request.get_full_path())
    ip = request.GET.get('ip', '127.0.0.1:8081')
    topo_p1 = request.GET.get('topop1', '0')
    topo_p2 = request.GET.get('topop2', '0')
    rfw = request.GET.get('rfw', '{}')
    rr = request.GET.get('rr', '{}')
    rLb = request.GET.get('rLb', '{}')
    funcs = request.GET.get('funcs', '')
    funcs = funcs.split(',')
    print(funcs)
    fs = ""
    #switchID = request.GET.get('id', '0000')
    for i in funcs:
        if fs != "":
            fs = fs + ","
        #print("i: "+i)
        if i != "firewall" and i != "loadBalancer" and i != "router":
            chain = Chain.objects.get(id=i)
            objs_json = chain.html
            nfs = json.loads(objs_json)
            #print("nfs: ")
            #print(nfs)
            orden = [None] * chain.size
            for pos in nfs:
                #print("pos: " + pos)
                nf = nfs[pos]
                #print("nf: " + nf)
                orden[int(pos)] = nf
            #print("orden")
            #print(orden)
            for f in range(0, len(orden)):  # 0 < f < len(orden)
                if f > 0:
                    fs = fs + ","
                #print("orden["+str(f)+"]: "+orden[f])
                fs = fs + orden[f]
        else:
            fs = fs + i
    #print("fs:")
    #print(fs)
    url = 'http://' + ip + '/launcher?f=' + fs + '&tp1=' + topo_p1 + '&tp2=' + topo_p2
    ex = Execution.objects.filter(ip=ip, state=1)
    #print(len(ex.values()))
    if (len(ex.values()) == 0):
        #print("new")
        e = Execution(nfs=fs, ip=ip, state=1, url=currentURL)
        e.save()
        return render(
            request, 'status.html', {
                'type': 'new',
                'ip': ip,
                'topo_p1': topo_p1,
                'topo_p2': topo_p2,
                'funcs': fs,
                'url': url,
                'idExec': e.id,
                'rfw': rfw,
                'rr': rr,
                'rLb': rLb
            })
    else:
        exe_obj = list(ex)
        return render(
            request, 'status.html', {
                'type': 'old',
                'ip': ip,
                'topo_p1': topo_p1,
                'topo_p2': topo_p2,
                'funcs': fs,
                'url': url,
                'idExec': exe_obj[0].id,
                'rfw': rfw,
                'rr': rr,
                'rLb': rLb
            })
예제 #25
0
def getURLS(request):

    obj = request.get_full_path()

    return render(request, 'base.html', {'output': obj})
예제 #26
0
def forumJump(request, name):
    url = request.get_full_path() + 'page=1/'
    return HttpResponseRedirect(url)
예제 #27
0
def choose_plugins(request):
    if not request.user.is_authenticated() or not request.user.has_perm('smartshark.start_collection'):
        messages.error(request, 'You are not authorized to perform this action.')
        return HttpResponseRedirect('/admin/smartshark/project')

    project = get_object_or_404(Project, pk=request.GET.get('project_id'))

    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        if 'cancel' in request.POST:
            return HttpResponseRedirect('/admin/smartshark/project')

        # create a form instance and populate it with data from the request:
        form = ProjectForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            plugin_ids = []
            interface = PluginManagementInterface.find_correct_plugin_manager()

            # check requirements
            for plugin in form.cleaned_data['plugins']:
                plugin_ids.append(str(plugin.id))

                # check for each plugin if required plugin is set
                '''
                missing_plugins = []
                for req_plugin in plugin.requires.all():
                    if req_plugin not in form.cleaned_data['plugins']:
                        missing_plugins.append(str(req_plugin))
                if missing_plugins:
                    messages.error(request, 'Not all requirements for plugin %s are met. Plugin(s) %s is/are required!'
                                   % (str(plugin), ', '.join(missing_plugins)))
                    return HttpResponseRedirect(request.get_full_path())
                '''
                # check if schema problems exist between plugins
                # TODO

                # if plugin with this project is in plugin execution and has status != finished | error -> problem
                for req_plugin in plugin.requires.all():
                    logger.debug("Looking at required plugin %s" % str(req_plugin))

                    # todo: implement check for plugins taking into account the plugin version e.g., if vcsshark-0.10 is required
                    # also allow vcsshark-0.11 or newer (if info.json allows that (>=))
                    #if not _check_if_at_least_one_execution_was_successful(req_plugin, project):
                    #    messages.error(request,
                    #                   'Not all requirements for plugin %s are met. Plugin %s was not executed '
                    #                   'successfully for project %s before!'
                    #                   % (str(plugin), str(req_plugin), str(project)))
                    #    return HttpResponseRedirect(request.get_full_path())

                    logger.debug("At least one plugin execution for plugin %s was successful." % str(req_plugin))

                # Update job information
                plugin_executions = PluginExecution.objects.all().filter(plugin=plugin, project=project)

                # Get all jobs from all plugin_executions which did not terminate yet
                jobs = []
                for plugin_execution in plugin_executions:
                    jobs.extend(Job.objects.filter(plugin_execution=plugin_execution, status='WAIT').all())

                # Update the job stati for these jobs
                job_stati = interface.get_job_stati(jobs)
                i = 0
                for job in jobs:
                    job.status = job_stati[i]
                    job.save()

                # check if some plugin has unfinished jobs
                has_unfinished_jobs = False
                for plugin_execution in plugin_executions:
                    if plugin_execution.has_unfinished_jobs():
                        has_unfinished_jobs = True

                if has_unfinished_jobs:
                    messages.error(request, 'Plugin %s is already scheduled for project %s.' % (str(plugin),
                                                                                                project))
                    return HttpResponseRedirect(request.get_full_path())

            return HttpResponseRedirect('/smartshark/project/collection/start?plugins=%s&project_id=%s' %
                                        (','.join(plugin_ids), request.GET.get('project_id')))

    # if a GET (or any other method) we'll create a blank form
    else:
        form = ProjectForm()

    return render(request, 'smartshark/project/action_collection.html', {
        'form': form,
        'projects': [project],

    })
예제 #28
0
def getImageDetaileJson(request):
    imageid = request.get_full_path().split('/')[2]
    url = "http://192.168.153.86:4243/images/%s/json" %(imageid)
    data = urllib.request.urlopen(url).read().decode()
    return HttpResponse(data,content_type='application/json')
예제 #29
0
def imagedetaile(request):
    #print (request.get_full_path())
    imageid = request.get_full_path().split('/')[2]
    return render_to_response('imagedetaile.html',{'imageid': imageid})
예제 #30
0
    def test(request, *args, **kwargs):
        # redirect
        if request.get_host() == 'www.chalaoshi.cn':
            return HttpResponsePermanentRedirect('https://chalaoshi.cn' +
                                                 request.get_full_path())

        test_ua(request)
        if request.ua_is_pc:
            copyright = True
            return render_to_response('pc.html', locals())

        # add uuid
        uuid = -1
        ip = request.META['REMOTE_ADDR']

        if not 'uuid' in request.session and 'uuid' in request.COOKIES:
            request.session['uuid'] = request.COOKIES['uuid']

        if not 'uuid' in request.session:
            uuid = generate_uuid(ip)
        else:
            uuid = request.session['uuid']
            try:
                uuid = int(uuid)
            except:
                uuid = generate_uuid(ip)
        request.session['uuid'] = uuid

        # check new openid
        redirect = request.GET.get('redirect', '')
        if redirect == 'openid_callback':
            pass

        # SNS visit log
        fr = request.GET.get('from', '')
        if not fr == '':
            # save visit log if from SNS
            log = SNSVisitLog()
            log.ip = request.META['REMOTE_ADDR']
            log.source = fr
            log.path = request.get_full_path()
            log.uuid = uuid
            log.save()

        # add wx js signature
        request.wx = wx_js_sign('https://' + request.get_host() +
                                request.get_full_path())

        # redirect to OpenID url
        response = None
        #if 'openid' not in request.session and request.ua_is_wx:
        #    from urllib import quote
        #    callback_url = quote(settings.HOST_NAME+'/wechat/wx_userinfo_callback')
        #    request.session['redirect'] = 'https://'+request.get_host()+request.get_full_path()
        #    response = HttpResponseRedirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect' % (settings.WECHAT['APPID'], callback_url, settings.WECHAT['TOKEN']))
        #else:
        #    if request.ua_is_wx:
        #        oid = OpenID.get_or_create(request.session['openid'], uuid)
        #        request.session['uuid'] = oid.uuid

        response = func(request, *args, **kwargs)
        response.set_cookie('uuid', '', expires=-1)

        return response
예제 #31
0
파일: views.py 프로젝트: dhawalnegi1/bfs2
def internal_server_error_view(request):
    error_url = request.get_full_path()
    template_name = "500.html"
    context = {"error_url": error_url}
    return render(request, template_name, context)
예제 #32
0
def search_show(request):
    """
    search_show - 검색 결과 출력 창 
    """
    if request.method == 'GET':
        # 경로 저장용 세션
        request.session['prev'] = request.get_full_path()
        print(request.session['prev'])

        key = request.session['country']
        if key:
            # 데이터 가져오기
            country_name = request.session['country']
            tmp_year = request.session['year']
            year = "gdp_" + str(tmp_year)
            sql = "SELECT " + year + " FROM SERVICE_GDPTABLE WHERE COUNTRYNAME = '" + country_name + "'"
            cursor.execute(sql)
            data = cursor.fetchone()
            avg = GDPTable.object.aggregate(gdp_avg=Avg(year))

            # 그래프 그리기
            plot_font()
            y = [float(data[0]), float(avg['gdp_avg'])]
            x = [(str(tmp_year) + "년 " + country_name + "의 GDP"),
                 str(tmp_year) + "년 " + "평균 GDP"]
            print(x)
            y = [float(data[0]), float(avg['gdp_avg'])]
            # print (x, y)

            try:
                sql1 = "SELECT * FROM SERVICE_NATIONDATATABLE WHERE COUNTRYNAME = '" + country_name + "'"
                cursor.execute(sql1)
                data1 = cursor.fetchall()
                print(type(data1))
                img_data = []
                for i in data1[0]:
                    tmp = str(i).replace(" ", "")
                    img_data.append(tmp)
                print("**", img_data)
                flag = img_data[-1]
                loc = img_data[-2]
                real_img_data = img_data[1:4]

                if loc == 'no_value' or flag == 'no_value':
                    print("tlqkf", loc)

                    file1 = open('./static/files/no_image.jpg', 'rb')
                    noimg = file1.read()
                    img64 = b64encode(noimg).decode("utf-8")
                    data4 = "data:;base64,{}".format(img64)
                    if loc == 'no_value':
                        print("no loc")
                        loc = data4

                    if flag == 'no_value':
                        print("no flag")
                        flag = data4

            except:
                real_img_data = ["no_data", "no_data", "no_data"]
                file1 = open('./static/files/no_image.jpg', 'rb')
                noimg = file1.read()
                img64 = b64encode(noimg).decode("utf-8")
                data4 = "data:;base64,{}".format(img64)
                loc = data4
                flag = data4

            dict1 = dict()
            dict1[country_name + " GDP_in " + str(tmp_year)] = data[0]
            dict1["Average GDP_in " + str(tmp_year)] = float(avg['gdp_avg'])
            country_name = country_name.replace(" ", "_")
            FILE_NAME = country_name + "_GDP_in_" + str(tmp_year) + ".json"
            FILE_PATH = "./static/files/" + FILE_NAME
            html_file_path = "/static/files/" + FILE_NAME
            with open(FILE_PATH, "w") as json_file:
                json.dump(dict1, json_file)

            return render(
                request, 'service/search_show.html', {
                    "xlist": x,
                    "list": y,
                    'country': country_name,
                    "year": tmp_year,
                    "file_name": html_file_path,
                    "img_data": real_img_data,
                    "flag": flag,
                    "loc": loc
                })

        return render(request, 'service/search_show.html')

    elif request.method == 'POST':
        tmp_year = request.POST["year"]
        country_name = request.POST["country_name"]

        request.session['country'] = country_name
        request.session['year'] = tmp_year
        return redirect('/service/search_show')
예제 #33
0
def containercommit(request):
    username = request.session.get('username')
    msg = ''
    departmentobj = Project.objects.all()
    #print(departmentobj)
    if request.method == "POST":
        path = request.get_full_path()
        #print(path)
        containerid = path.split('/')[3][:12]
        #print(containerid)
        commitimagename = request.POST.get('commitimagename')
        #print(commitimagename)
        commitdeparment = request.POST.get('department')
        print(commitdeparment)
        commitbz = request.POST.get('bz')
        print(commitbz)
        imageexist = ImageName.objects.filter(
            imagename=commitimagename)  #判断容器名是否存在
        if imageexist:
            msg = "容器名已存在!!!"
        else:
            try:
                container = Container.objects.get(
                    containerid__startswith=containerid)
            except:
                msg = '数据库查询有问题'
            #print(container.password,container.containername,container.containerhost,container.dockerhost)
            dockerip = container.dockerhost  #获取docker主机IP地址
            docker = DockerHost.objects.get(ip=dockerip)  #根据ip地址查询
            dockerpassword = docker.hostpassword  #获取密码
            #print(dockerpassword)

            commitresult = rundockercmd.commitContainer(
                rundockercmd.sshClient(dockerip, dockerpassword), containerid,
                commitimagename)
            msg = 'commit 失败' + commitresult
            if commitresult:
                registryup = registryjson.getregistryjson(
                    registryjson.sshClient(dockerip, dockerpassword))
                m = re.findall(r"repositories", registryup)
                if m:
                    print(commitresult)
                    tagresult = rundockercmd.pushImage(
                        rundockercmd.sshClient(dockerip, dockerpassword),
                        commitresult, commitimagename)
                    print(tagresult)
                    msg = '提交远程完成!'
                    createimage = ImageName.objects.create(
                        username=username,
                        imagename=commitimagename,
                        departmentname=commitdeparment,
                        bz=commitbz)
                else:
                    msg = '私有仓库有问题,请联管理员'
                return render_to_response('containercommit.html', {'msg': msg})
            else:
                return render_to_response('containercommit.html', {
                    'commitresult': commitresult,
                    'msg': msg
                })
            return render_to_response('containercommit.html', {'msg': msg})
        return render_to_response('containercommit.html', {'msg': msg})
    return render_to_response('containercommit.html', {
        'msg': msg,
        'departmentobj': departmentobj,
        'username': username
    })