Beispiel #1
0
def host_add(request):
    """ 添加主机 """
    uf = HostForm()
    projects = Project.objects.all()
    services = Service.objects.all()
    if request.method == 'POST':
        uf_post = HostForm(request.POST)
        physics = request.POST.get('physics', '')
        ip = request.POST.get('eth1', '')
        if Host.objects.filter(eth1=ip):
            emg = u'添加失败, 该IP %s 已存在!' % ip
            return my_render('assets/host_add.html', locals(), request)
        if uf_post.is_valid():
            zw = uf_post.save(commit=False)
            # zw.mac = str(request.POST.getlist("mac")[0]).replace(':', '-').strip(" ")
            status = uf_post.cleaned_data['status']
            if physics:
                physics_host = get_object_or_404(Host, eth1=physics)
                zw.vm = physics_host
                zw.type = 1
            else:
                zw.type = 0
            zw.save()
            uf_post.save_m2m()
            host = Host.objects.get(eth1=ip)
            server_info(host.uuid)
            smg = u'主机%s添加成功!' % ip

            return render_to_response('assets/host_add.html',
                                      locals(),
                                      context_instance=RequestContext(request))
    return render_to_response('assets/host_add.html',
                              locals(),
                              context_instance=RequestContext(request))
Beispiel #2
0
def host_add(request):
    if not request.user.has_perm('cmdb.add_host'):
        raise PermissionDenied

    t = request.GET.get('t', '2')  # 资产类型ID
    active = 'cmdb_host_1_active' if t == '1' else 'cmdb_host_2_active'

    context = {active: 'active'}
    if request.method == 'POST':
        # import ipdb;ipdb.set_trace()
        newhost = QueryDict(mutable=True)
        newhost.update(request.POST)
        newhost.update({'asset_type': t})
        form = HostForm(newhost)
        if form.is_valid():
            form.save()
            ref_url = request.POST.get('ref_url', '/')
            return redirect(ref_url)
    else:
        form = HostForm()
        ref_url = request.META.get('HTTP_REFERER', '/')  # 来源URL,供POST成功后返回
        context.update({'ref_url': ref_url})

    context.update({'form': form})
    html = 'host_2.html'

    return render(request, html, context)
Beispiel #3
0
def edit(request):
    '''Edit a host's information.'''
    # The request method used (GET, POST, etc) determines what dict 'context'
    # gets filled with.
    context = {}

    # If we have a non-empty POST request, that means
    # the user is submitting / loading the form.
    if request.POST:

        # 'update_form' is a hidden tag in our template's form.
        # If it exists in our POST, then the user is submitting the form.
        # Otherwise, the user is loading the form.
        if 'update_form' not in request.POST:
            host_ip = request.session['last-host']
            host = get_object_or_404(Host, ipv4_address=host_ip)
            context['host'] = host
            form = HostForm(instance=host)
        else:
            # Retrieve IP addr user entered into form.
            # Use that IP to get respective Host object.
            host_ip = request.session['last-host']
            host = get_object_or_404(Host, ipv4_address=host_ip)

            # Load form with provided information so we can save the form as
            # an object. (See forms.py and docs on ModelForms for more info)
            form = HostForm(request.POST, instance=host)

            # form.is_valid() checks that updated instance object's new attributes
            # are valid. Calling form.save() will actually save them to the db.
            if form.is_valid():

                # Save attributes from form into those of a Host object.
                form.save()

                # Get ip addr of updated Host so we can direct user to its page
                # after editing.
                new_ip = request.session['last-host']

                return HttpResponseRedirect('/hosts/search/?input_ip=%s' %
                                            new_ip)

    # Request method was empty, so user wants to create new Host.
    # Create empty form.
    else:
        if 'last-host' in request.session:
            host_ip = request.session['last-host']
            host = get_object_or_404(Host, ipv4_address=host_ip)
            context['host'] = host
            form = HostForm(instance=host)
        else:
            form = HostForm()

    # Add new CSRF token and form to context.
    context.update(csrf(request))
    context['form'] = form
    return render(request, 'hosts/edit_host.html', context)
Beispiel #4
0
def asset_add(request):
    temp_name = "cmdb/cmdb-header.html"
    if request.method == 'POST':
        form = HostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('asset_list')
    else:
        form = HostForm()
    return render(request, 'cmdb/asset_add.html', locals())
Beispiel #5
0
def add(request, template_name):
    if request.method == 'POST':
        form = HostForm(request.POST)
        if form.is_valid():
            host_info = form.save()
            host_info.save()
            return HttpResponseRedirect('/assets/')
            #return HttpResponseRedirect('/')
    else:
        form = HostForm()
    return render_to_response(template_name, {
        'user': request.user,
        'form': form,
    })
Beispiel #6
0
def asset_edit(request, id):
    status = 0
    asset_types = ASSET_TYPE
    host = Host.objects.get(id=id)

    if request.method == 'POST':
        form = HostForm(request.POST, instance=host)
        if form.is_valid():
            form.save()
            status = 1
        else:
            status = 2
    else:
        form = HostForm(instance=host)
    return render(request, 'cmdb/asset_edit.html', locals())
Beispiel #7
0
def host_add():
    form = HostForm()
    if form.validate_on_submit():
        data = form.data
        name_count = Host.query.filter_by(name=data["host_name"]).count()
        if name_count == 1:
            flash("主机名已经存在!", "err")
            return redirect(url_for("admin.host_add"))
        outernetip_num = Host.query.filter_by(
            outernet_ip=data["outernet_ip"]).count()
        if outernetip_num == 1:
            flash("外网IP已经存在!", "err")
            return redirect(url_for("admin.host_add"))
        host = Host(
            name=data["host_name"],
            system=data["system"],
            outernet_ip=data["outernet_ip"],
            intranet_ip=data["intranet_ip"],
            cpu=data["cpu"],
            memory=data["memory"],
            disk=data["disk"],
            username=data["username"],
            password=data["password"],
            port=data["port"],
            ssh_port=data["ssh_port"],
            status=data["status"],
        )
        db.session.add(host)
        db.session.commit()
        flash("添加主机成功", "ok")
        return redirect(url_for("admin.host_list", page=1))
    return render_template("admin/host_add.html", form=form)
Beispiel #8
0
def setHost(name, url_back):
    """edit host

    Edit an existing host

    Arguments:
        name - name of the host to be edited
        url_back - url for redirecting when finished

    Return: if form validates edit the host, if doesn't show a page with the
        errors
    """
    form = HostForm(request.form)

    host = APIObject(name, 'host')
    host_to_edit = host.show()

    if request.method == 'POST' and form.validate():
        host.edit(new_name=app.config['ID_COLE'] + 'HOST_' + form.name.data,
                  ipv4_address=form.ipv4_address.data)
        api.api_call('publish')
        flash('Edited team')
        return redirect(url_for(url_back))

    return render_template('edit-host.html',
                           form=form,
                           host_to_edit=host_to_edit,
                           url_back=url_back)
Beispiel #9
0
def addHost(group_name, url_back):
    """add host
    Add a new host inside a group

    Arguments:
        group_nam - the name of the group where the host has to be added
        url_back - url for redirecting when finished

    Return: if form validates, create the host and add it to the group, if
        doesn't render a page with the errors
    """
    form = HostForm(request.form)
    if request.method == 'POST' and form.validate():
        host = APIObject('HOST_' + form.name.data, 'host')
        add = host.add(ipv4_address=form.ipv4_address.data)
        if not add.success:
            if 'errors' in add.res_obj['data']:
                message = add.res_obj['data']['errors'][0]['message']
                if message[:26] == 'More than one object named':
                    flash('A computer with that name already exists')
            if 'warnings' in add.res_obj['data']:
                message = add.res_obj['data']['warnings'][0]['message']
                if message[:37] == 'More than one object have the same IP':
                    flash('A computer with this IP already exists')
        else:
            host.add_to_group('set-group', group_name)
            api.api_call('publish')
            flash('Equipment added')
        return redirect(url_for(url_back))
    else:
        return render_template('form-errors.html',
                               form=form,
                               url_back=url_back)
Beispiel #10
0
def host_register(request):
    gRegister = False
    if request.method == 'POST':
        host_form = HostForm(data=request.POST)
        if host_form.is_valid():
            user = host_form.save()
            user.set_password(user.password)
            user.save()
            gRegister = True
            return HttpResponseRedirect('/hackathon/api/')
        else:
            print host_form.errors
    else:
        guide_form = HostForm()
    context = {'guide_form': guide_form, 'registered': gRegister}
    return render(request, 'hackathon/host.html', context)
Beispiel #11
0
def host_edit(id=None):
    form = HostForm()
    host = Host.query.get_or_404(id)
    if request.method == "GET":
        form.status.data = host.status
    if form.validate_on_submit():
        data = form.data
        host_num = Host.query.filter_by(name=data["host_name"]).count()
        if host.name != data["host_name"] and host_num == 1:
            flash("主机名已经存在!", "err")
            return redirect(url_for("admin.host_edit", id=id))
        outernetip_num = Host.query.filter_by(
            outernet_ip=data["outernet_ip"]).count()
        if host.outernet_ip != data["outernet_ip"] and outernetip_num == 1:
            flash("外网IP已经存在!", "err")
            return redirect(url_for("admin.host_edit", id=id))
        host.name = data["host_name"]
        host.system = data["system"]
        host.outernet_ip = data["outernet_ip"]
        host.intranet_ip = data["intranet_ip"]
        host.cpu = data["cpu"]
        host.memory = data["memory"]
        host.disk = data["disk"]
        host.username = data["username"]
        host.password = data["password"]
        host.port = data["port"]
        host.ssh_port = data["ssh_port"]
        host.status = data["status"]
        db.session.add(host)
        db.session.commit()
        flash("修改主机成功!", "ok")
        return redirect(url_for("admin.host_list", page=1))
    return render_template("admin/host_edit.html", form=form, host=host)
Beispiel #12
0
def hosts(request, event_id):
    event = get_object_or_404(Event, id=event_id)
    form = HostForm(event=event, data=(request.POST or None))
    if form.is_valid():
        form.save()
        return redirect(event)
    template = "events/_hosts.html" if request.is_ajax() else "events/hosts.html"
    return render_to_response(template, locals(), context_instance=RequestContext(request))
Beispiel #13
0
def host_register(request):
    user = request.user
    if user.is_authenticated:
        if request.method == 'POST':
            host_form = HostForm(data=request.POST)
            if host_form.is_valid():
                instance = host_form.save(commit=False)
                instance.user = request.user
                instance.save()
                return HttpResponseRedirect('/edit_userpage/')
            else:
                print host_form.errors
    else:
        return HttpResponseRedirect('/')
    guide_form = HostForm()
    context = {'guide_form': guide_form}
    return render(request, 'users/host.html', context)
Beispiel #14
0
def host_edit(request):
    """ 修改主机 """
    uuid = request.GET.get('uuid')
    host = get_object_or_404(Host, uuid=uuid)
    uf = HostForm(instance=host)
    project_all = Project.objects.all()
    project_host = host.business.all()
    projects = [p for p in project_all if p not in project_host]

    service_all = Service.objects.all()
    service_host = host.service.all()
    services = [s for s in service_all if s not in service_host]
    username = request.user.username
    if request.method == 'POST':
        physics = request.POST.get('physics', '')
        uf_post = HostForm(request.POST, instance=host)
        if uf_post.is_valid():
            zw = uf_post.save(commit=False)
            zw.mac = str(request.POST.getlist("mac")[0]).replace(
                ':', '-').strip(" ")
            request.POST = request.POST.copy()
            if physics:
                physics_host = get_object_or_404(Host, eth1=physics)
                request.POST['vm'] = physics_host.uuid
                if host.vm:
                    if str(host.vm.eth1) != str(physics):
                        zw.vm = physics_host
                else:
                    zw.vm = physics_host
                zw.type = 1
            else:
                request.POST['vm'] = ''
                zw.type = 0

            zw.save()
            uf_post.save_m2m()
            new_host = get_object_or_404(Host, uuid=uuid)
            info = get_diff(uf_post.__dict__.get('initial'), request.POST)
            db_to_record(username, host, info)
            return HttpResponseRedirect('/assets/host_detail/?uuid=%s' % uuid)

    return render_to_response('assets/host_edit.html',
                              locals(),
                              context_instance=RequestContext(request))
Beispiel #15
0
def showGroupMembers(group_name, url_back):
    """show group members

    Show the hosts of each group, allow the user to add a new host to the group

    Arguments:
        group_name - the group's name
        url_back - url for redirecting when finished

    Return: render the show group members page
    """
    form = HostForm(request.form)
    members = APIObject(group_name, 'group').show_members()
    return render_template('show-group-members.html',
                           members=members,
                           form=form,
                           group_name=group_name,
                           url_back=url_back)
Beispiel #16
0
def host_create():
    if not can_create(current_user):
        abort(401)

    form = HostForm(request.form)

    db_session = DBSession()
    fill_jump_hosts(db_session, form.jump_host.choices)
    fill_regions(db_session, form.region.choices)
    fill_software_profiles(db_session, form.software_profile.choices)

    if request.method == 'POST' and form.validate():
        db_session = DBSession()
        try:
            host = get_host(db_session, form.hostname.data)
            if host is not None:
                return render_template('host/edit.html',
                                       form=form,
                                       duplicate_error=True)

            create_or_update_host(
                db_session=db_session,
                hostname=form.hostname.data,
                region_id=form.region.data,
                location=form.location.data,
                roles=form.roles.data,
                software_profile_id=form.software_profile.data,
                connection_type=form.connection_type.data,
                host_or_ip=form.host_or_ip.data,
                username=form.username.data,
                password=form.password.data,
                enable_password=form.enable_password.data,
                port_number=form.port_number.data,
                jump_host_id=form.jump_host.data,
                created_by=current_user.username)

        finally:
            db_session.rollback()

        return redirect(url_for('home'))

    return render_template('host/edit.html', form=form)
Beispiel #17
0
def host_edit_batch(request):
    """ 批量修改主机 """
    uf = HostForm()
    username = request.user.username
    projects = Project.objects.all()
    services = Service.objects.all()
    if request.method == 'POST':
        ids = str(request.GET.get('uuid', ''))
        env = request.POST.get('env', '')
        idc = request.POST.get('idc', '')
        host_application = request.POST.get('host_application', '')
        business = request.POST.getlist('business', '')
        services = request.POST.getlist('service', '')
        cabinet = request.POST.get('cabinet', '')
        editor = request.POST.get('editor', '')
        uuid_list = ids.split(",")

        for uuid in uuid_list:
            record_list = []
            host = get_object_or_404(Host, uuid=uuid)
            if env:
                if not host.env:
                    info = u'无'
                else:
                    info = host.env
                if env != host.env:
                    text = u'环境' + u'由 ' + info + u' 更改为 ' + env
                    record_list.append(text)
                    host.env = env

            if idc:
                get_idc = get_object_or_404(IDC, uuid=idc)

                if host.idc != get_idc.name:
                    if not host.idc:
                        text = u'IDC' + u'由 ' + "none" + u' 更改为 ' + get_idc.name
                    else:
                        text = u'IDC' + u'由 ' + host.idc.name + u' 更改为 ' + get_idc.name
                    record_list.append(text)
                    host.idc = get_idc

            if host_application:
                if host_application != host.host_application:
                    text = u'主机应用' + u'由 ' + host.host_application + u' 更改为 ' + host_application
                    record_list.append(text)
                    host.host_application = host_application

            if business:
                old, new, project_list = [], [], []
                for s in host.business.all():
                    project_name = s.service_name
                    old.append(project_name)
                for s in business:
                    project = Project.objects.get(uuid=s)
                    project_name = project.service_name
                    new.append(project_name)
                    project_list.append(project)
                if old != new:
                    text = u'所属业务' + u'由 ' + ','.join(
                        old) + u' 更改为 ' + ','.join(new)
                    record_list.append(text)
                    host.business = project_list

            if services:
                old, new, service_list = [], [], []
                for s in host.service.all():
                    service_name = s.name
                    old.append(service_name)
                for s in services:
                    service = Service.objects.get(uuid=s)
                    service_name = service.name
                    new.append(service_name)
                    service_list.append(service)
                if old != new:
                    text = u'运行服务' + u'由 ' + ','.join(
                        old) + u' 更改为 ' + ','.join(new)
                    record_list.append(text)
                    host.service = service_list

            if cabinet:
                if not host.cabinet:
                    info = u'无'
                else:
                    info = host.cabinet
                if cabinet != host.cabinet:
                    text = '机柜号' + u'由 ' + info + u' 更改为 ' + cabinet
                    record_list.append(text)
                    host.cabinet = cabinet

            if editor:
                if editor != host.editor:
                    text = '备注' + u'由 ' + host.editor + u' 更改为 ' + editor
                    record_list.append(text)
                    host.editor = editor

            if len(record_list) != 0:
                host.save()
                HostRecord.objects.create(host=host,
                                          user=username,
                                          content=record_list)

        return my_render('assets/host_edit_batch_ok.html', locals(), request)
    return my_render('assets/host_edit_batch.html', locals(), request)
Beispiel #18
0
def host_edit(hostname):
    db_session = DBSession()

    host = get_host(db_session, hostname)
    if host is None:
        abort(404)

    form = HostForm(request.form)
    fill_jump_hosts(db_session, form.jump_host.choices)
    fill_regions(db_session, form.region.choices)
    fill_software_profiles(db_session, form.software_profile.choices)

    if request.method == 'POST' and form.validate():
        if not can_edit(current_user):
            abort(401)

        # Editing a hostname which has already existed in the database.
        if hostname != form.hostname.data and get_host(
                db_session, form.hostname.data) is not None:
            return render_template('host/edit.html',
                                   form=form,
                                   duplicate_error=True)

        create_or_update_host(
            db_session=db_session,
            hostname=form.hostname.data,
            region_id=form.region.data,
            location=form.location.data,
            roles=form.roles.data,
            software_profile_id=form.software_profile.data,
            connection_type=form.connection_type.data,
            host_or_ip=form.host_or_ip.data,
            username=form.username.data,
            password=form.password.data if len(form.password.data) > 0 else
            host.connection_param[0].password,
            enable_password=form.enable_password.data
            if len(form.enable_password.data) > 0 else
            host.connection_param[0].enable_password,
            port_number=form.port_number.data,
            jump_host_id=form.jump_host.data,
            created_by=current_user.username,
            host=host)

        return_url = get_return_url(request, 'home')

        if return_url is None:
            return redirect(url_for('home'))
        else:
            return redirect(url_for(return_url, hostname=hostname))
    else:
        # Assign the values to form fields
        form.hostname.data = host.hostname
        form.region.data = host.region_id
        form.software_profile.data = host.software_profile_id
        form.location.data = host.location
        form.roles.data = host.roles
        form.host_or_ip.data = host.connection_param[0].host_or_ip
        form.username.data = host.connection_param[0].username
        form.jump_host.data = host.connection_param[0].jump_host_id
        form.connection_type.data = host.connection_param[0].connection_type
        form.port_number.data = host.connection_param[0].port_number
        if not is_empty(host.connection_param[0].password):
            form.password_placeholder = 'Use Password on File'
        else:
            form.password_placeholder = 'No Password Specified'

        if not is_empty(host.connection_param[0].enable_password):
            form.enable_password_placeholder = 'Use Password on File'
        else:
            form.enable_password_placeholder = 'No Password Specified'

        return render_template('host/edit.html', form=form)