コード例 #1
0
ファイル: deployment.py プロジェクト: 4i60r/ralph
 def clean_new_ip(self):
     old_ip = self.cleaned_data.get('address')
     new_ip = self.cleaned_data['new_ip']
     try:
         new_ip = str(ipaddr.IPAddress(new_ip))
     except ValueError:
         raise forms.ValidationError("Malformed IP address.")
     rdomain = '.'.join(
         list(reversed(new_ip.split('.')))[1:]
     ) + '.in-addr.arpa'
     if not Domain.objects.filter(name=rdomain).exists():
         raise forms.ValidationError("No RevDNS domain for address.")
     try:
         ipaddress = IPAddress.objects.get(address=new_ip)
     except IPAddress.DoesNotExist:
         if Record.objects.filter(content=new_ip).exists():
             raise forms.ValidationError("Address already in DNS.")
         if get_revdns_records(new_ip).exists():
             raise forms.ValidationError("Address already in DNS.")
         if DHCPEntry.objects.filter(ip=new_ip).exists():
             raise forms.ValidationError("Address already in DHCP.")
     else:
         if ipaddress.device and not ipaddress.device.deleted:
             if not old_ip:
                 raise forms.ValidationError("Address in use.")
             device = Device.objects.get(ipaddress__address=old_ip)
             if ipaddress.device.id != device.id:
                 raise forms.ValidationError(
                     "Address used by %s" % device,
                 )
     return new_ip
コード例 #2
0
ファイル: forms.py プロジェクト: szaydel/ralph
    def __init__(self, records, hostnames, *args, **kwargs):
        super(DNSRecordsForm, self).__init__(*args, **kwargs)
        self.records = list(records)
        self.hostnames = hostnames

        def _dns_name_field(label=None, initial=None, **kwargs):
            kwargs.update(
                label=label,
                initial=initial,
                required=False,
                validators=[validate_domain_name],
                widget=AutocompleteWidget(
                    attrs={"class": "span12", "placeholder": label, "style": "min-width: 16ex"},
                    choices=[(n, n) for n in hostnames],
                ),
            )
            return forms.CharField(**kwargs)

        fields = [
            ("name", _dns_name_field),
            ("type", _dns_type_limited_field),
            ("content", _dns_char_field),
            ("ptr", _bool_field),
            ("del", _bool_field),
        ]
        for record in self.records:
            if record.type in ("A", "AAAA"):
                record.ptr = False
                for r in get_revdns_records(record.content).filter(content=record.name):
                    record.ptr = True
            prefix = "dns_%d_" % record.id
            _add_fields(self.fields, prefix, record, fields)
        fields = [
            ("name", _dns_name_field),
            ("type", _dns_type_limited_field),
            ("content", _dns_char_field),
            ("ptr", _bool_field),
            ("del", _bool_hidden_field),
        ]
        _add_fields(self.fields, "dns_new_", None, fields)
        if hostnames:
            self.fields["dns_new_name"].initial = list(hostnames)[0]
コード例 #3
0
ファイル: addresses.py プロジェクト: 4i60r/ralph
 def __init__(self, *args, **kwargs):
     self.hostnames = kwargs.pop('hostnames')
     self.ips = kwargs.pop('ips')
     limit_types = kwargs.pop('limit_types')
     super(DNSRecordForm, self).__init__(*args, **kwargs)
     self.is_extra = False
     self.fields['type'].choices = [(t, t) for t in limit_types]
     if self.instance.type in ('A', 'AAAA') and get_revdns_records(
             self.instance.content
     ).filter(
             content=self.instance.name
     ).exists():
         self.fields['ptr'].initial = True
     if not self.instance.name and self.hostnames:
         hostname = list(self.hostnames)[0]
         self.fields['name'].initial = hostname
         self.instance.name = hostname
     if not self.instance.type:
         self.fields['type'].initial = 'A'
         self.instance.type = 'A'
         self.is_extra = True
     self.fields['name'].widget.choices = [(n, n) for n in self.hostnames]
     self.fields['content'].widget.choices = [(ip, ip) for ip in self.ips]
コード例 #4
0
ファイル: dhcp_conf.py プロジェクト: andrzej-jankowski/ralph
def _get_first_rev(ips):
    for ip in ips:
        for rev in get_revdns_records(ip):
            return rev.content
    return ips[0] if ips else ''
コード例 #5
0
ファイル: common.py プロジェクト: szaydel/ralph
def _dns_delete_record(form, record, request):
    if record.type == 'A':
        for r in get_revdns_records(record.content).filter(content=record.name):
            r.saving_user = request.user
            r.delete()
            messages.warning(request, "PTR record deleted.")
コード例 #6
0
ファイル: common.py プロジェクト: damjanek/ralph
 def post(self, *args, **kwargs):
     self.object = self.get_object()
     profile = self.request.user.get_profile()
     if not profile.has_perm(self.edit_perm, self.object.venture):
         return HttpResponseForbidden(
             "You don't have permission to edit this."
         )
     if 'dns' in self.request.POST:
         dns_records = self.get_dns(self.limit_types)
         ips = {ip.address for ip in self.object.ipaddress_set.all()}
         self.dns_formset = DNSFormSet(
             self.request.POST,
             queryset=dns_records,
             prefix='dns',
             hostnames=self.get_hostnames(),
             limit_types=self.limit_types,
             ips=ips,
         )
         if self.dns_formset.is_valid():
             for form in self.dns_formset.extra_forms:
                 # Bind the newly created records to domains.
                 if form.has_changed():
                     form.instance.domain = get_domain(form.instance.name)
                     # Save the user for newly added records
                     form.instance.saving_user = self.request.user
             for form in self.dns_formset.initial_forms:
                 if form.has_changed():
                     # Save the user for modified records
                     form.instance.saving_user = self.request.user
                     # Make sure the PTR record is updated on field change
                     if form.instance.ptr and (
                         'name' in form.changed_data or
                         'content' in form.changed_data
                     ):
                         r = Record.objects.get(id=form.instance.id)
                         for ptr in get_revdns_records(
                                 r.content).filter(content=r.name):
                             ptr.saving_user = self.request.user
                             ptr.delete()
                             messages.warning(
                                 self.request,
                                 "PTR record for %s and %s deleted." % (
                                     r.name,
                                     r.content,
                                 ),
                             )
                         form.changed_data.append('ptr')
             self.dns_formset.save()
             for r, data in self.dns_formset.changed_objects:
                 # Handle PTR creation/deletion
                 if 'ptr' in data:
                     if r.ptr:
                         try:
                             set_revdns_record(r.content, r.name)
                         except DNSError as e:
                             messages.error(self.request, unicode(e))
                         else:
                             messages.warning(
                                 self.request,
                                 "PTR record for %s and %s created." % (
                                     r.name,
                                     r.content,
                                 ),
                             )
                     else:
                         for ptr in get_revdns_records(
                                 r.content).filter(content=r.name):
                             ptr.saving_user = self.request.user
                             ptr.delete()
                             messages.warning(
                                 self.request,
                                 "PTR record for %s and %s deleted." % (
                                     r.name,
                                     r.content,
                                 ),
                             )
             for r in self.dns_formset.new_objects:
                 # Handle PTR creation
                 if r.ptr:
                     try:
                         set_revdns_record(r.content, r.name)
                     except DNSError as e:
                         messages.error(self.request, unicode(e))
                     else:
                         messages.warning(
                             self.request,
                             "PTR record for %s created." % r.content
                         )
             for r in self.dns_formset.deleted_objects:
                 # Handle PTR deletion
                 for ptr in get_revdns_records(
                         r.content).filter(content=r.name):
                     messages.warning(
                         self.request,
                         "PTR record for %s deleted." % r.name
                     )
                     ptr.saving_user = self.request.user
                     ptr.delete()
             messages.success(self.request, "DNS records updated.")
             return HttpResponseRedirect(self.request.path)
         else:
             messages.error(self.request, "Errors in the DNS form.")
     elif 'dhcp' in self.request.POST:
         dhcp_records = self.get_dhcp()
         macs = {e.mac for e in self.object.ethernet_set.all()}
         ips = {ip.address for ip in self.object.ipaddress_set.all()}
         self.dhcp_formset = DHCPFormSet(
             dhcp_records,
             macs,
             ips,
             self.request.POST,
             prefix='dhcp',
         )
         if self.dhcp_formset.is_valid():
             self.dhcp_formset.save()
             messages.success(self.request, "DHCP records updated.")
             return HttpResponseRedirect(self.request.path)
         else:
             messages.error(self.request, "Errors in the DHCP form.")
     elif 'ip' in self.request.POST:
         self.ip_formset = IPAddressFormSet(
             self.request.POST,
             queryset=self.object.ipaddress_set.order_by('address'),
             prefix='ip',
         )
         if self.ip_formset.is_valid():
             for form in self.ip_formset.extra_forms:
                 # Bind the newly created addresses to this device.
                 if form.has_changed():
                     form.instance.device = self.object
             self.ip_formset.save()
             messages.success(self.request, "IP addresses updated.")
             return HttpResponseRedirect(self.request.path)
         else:
             messages.error(self.request, "Errors in the addresses form.")
     return self.get(*args, **kwargs)