diff --git a/apps/assets/api.py b/apps/assets/api.py index 477150ec2..da363dee4 100644 --- a/apps/assets/api.py +++ b/apps/assets/api.py @@ -24,7 +24,7 @@ from common.mixins import IDInFilterMixin from common.utils import get_object_or_none from .hands import IsSuperUser, IsAppUser, IsValidUser, \ get_user_granted_assets, push_users -from .models import AssetGroup, Asset, IDC, SystemUser, AdminUser +from .models import AssetGroup, Asset, Cluster, SystemUser, AdminUser from . import serializers from .tasks import update_assets_hardware_info from .utils import test_admin_user_connective_manual @@ -41,12 +41,12 @@ class AssetViewSet(IDInFilterMixin, BulkModelViewSet): queryset = super(AssetViewSet, self).get_queryset() else: queryset = get_user_granted_assets(self.request.user) - idc_id = self.request.query_params.get('idc_id', '') + cluster_id = self.request.query_params.get('cluster_id', '') system_users_id = self.request.query_params.get('system_user_id', '') asset_group_id = self.request.query_params.get('asset_group_id', '') admin_user_id = self.request.query_params.get('admin_user_id', '') - if idc_id: - queryset = queryset.filter(idc__id=idc_id) + if cluster_id: + queryset = queryset.filter(cluster__id=cluster_id) if system_users_id: queryset = queryset.filter(system_users__id=system_users_id) if admin_user_id: @@ -84,17 +84,17 @@ class AssetGroupUpdateSystemUserApi(generics.RetrieveUpdateAPIView): permission_classes = (IsSuperUser,) -class IDCUpdateAssetsApi(generics.RetrieveUpdateAPIView): - """IDC update asset member""" - queryset = IDC.objects.all() - serializer_class = serializers.IDCUpdateAssetsSerializer +class ClusterUpdateAssetsApi(generics.RetrieveUpdateAPIView): + """Cluster update asset member""" + queryset = Cluster.objects.all() + serializer_class = serializers.ClusterUpdateAssetsSerializer permission_classes = (IsSuperUser,) -class IDCViewSet(IDInFilterMixin, BulkModelViewSet): - """IDC api set, for add,delete,update,list,retrieve resource""" - queryset = IDC.objects.all() - serializer_class = serializers.IDCSerializer +class ClusterViewSet(IDInFilterMixin, BulkModelViewSet): + """Cluster api set, for add,delete,update,list,retrieve resource""" + queryset = Cluster.objects.all() + serializer_class = serializers.ClusterSerializer permission_classes = (IsSuperUser,) diff --git a/apps/assets/forms.py b/apps/assets/forms.py index 902325310..d7d014a15 100644 --- a/apps/assets/forms.py +++ b/apps/assets/forms.py @@ -2,7 +2,7 @@ from django import forms from django.utils.translation import gettext_lazy as _ -from .models import IDC, Asset, AssetGroup, AdminUser, SystemUser +from .models import Cluster, Asset, AssetGroup, AdminUser, SystemUser from common.utils import validate_ssh_private_key, ssh_pubkey_gen, ssh_key_gen, get_logger @@ -14,7 +14,7 @@ class AssetCreateForm(forms.ModelForm): model = Asset fields = [ 'hostname', 'ip', 'public_ip', 'port', 'type', 'comment', - 'admin_user', 'idc', 'groups', 'status', 'env', 'is_active' + 'admin_user', "cluster", 'groups', 'status', 'env', 'is_active' ] widgets = { 'groups': forms.SelectMultiple( @@ -43,7 +43,7 @@ class AssetUpdateForm(forms.ModelForm): class Meta: model = Asset fields = [ - 'hostname', 'ip', 'port', 'groups', 'admin_user', 'idc', 'is_active', + 'hostname', 'ip', 'port', 'groups', 'admin_user', "cluster", 'is_active', 'type', 'env', 'status', 'public_ip', 'remote_card_ip', 'cabinet_no', 'cabinet_pos', 'number', 'comment' ] @@ -83,7 +83,7 @@ class AssetBulkUpdateForm(forms.ModelForm): class Meta: model = Asset fields = [ - 'assets', 'port', 'groups', 'admin_user', 'idc', + 'assets', 'port', 'groups', 'admin_user', "cluster", 'type', 'env', 'status', ] widgets = { @@ -139,7 +139,7 @@ class AssetGroupForm(forms.ModelForm): } -class IDCForm(forms.ModelForm): +class ClusterForm(forms.ModelForm): # See AdminUserForm comment same it assets = forms.ModelMultipleChoiceField( queryset=Asset.objects.all(), @@ -153,16 +153,16 @@ class IDCForm(forms.ModelForm): if kwargs.get('instance'): initial = kwargs.get('initial', {}) initial['assets'] = kwargs['instance'].assets.all() - super(IDCForm, self).__init__(*args, **kwargs) + super(ClusterForm, self).__init__(*args, **kwargs) def _save_m2m(self): - super(IDCForm, self)._save_m2m() + super(ClusterForm, self)._save_m2m() assets = self.cleaned_data['assets'] self.instance.assets.clear() self.instance.assets.add(*tuple(assets)) class Meta: - model = IDC + model = Cluster fields = ['name', "bandwidth", "operator", 'contact', 'phone', 'address', 'intranet', 'extranet', 'comment'] widgets = { @@ -356,6 +356,5 @@ class SystemUserUpdateForm(forms.ModelForm): } - class FileForm(forms.Form): file = forms.FileField() diff --git a/apps/assets/models/__init__.py b/apps/assets/models/__init__.py index 0414d03b3..52c68903e 100644 --- a/apps/assets/models/__init__.py +++ b/apps/assets/models/__init__.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # -from .idc import * +from .cluster import * from .user import * from .group import * from .asset import * diff --git a/apps/assets/models/asset.py b/apps/assets/models/asset.py index 9db42c938..cbb1bd59b 100644 --- a/apps/assets/models/asset.py +++ b/apps/assets/models/asset.py @@ -10,14 +10,14 @@ from django.db import models import logging from django.utils.translation import ugettext_lazy as _ -from . import IDC, AssetGroup, AdminUser, SystemUser +from . import Cluster, AssetGroup, AdminUser, SystemUser __all__ = ['Asset'] logger = logging.getLogger(__name__) -def get_default_idc(): - return IDC.initial() +def get_default_cluster(): + return Cluster.initial() class Asset(models.Model): @@ -47,7 +47,7 @@ class Asset(models.Model): groups = models.ManyToManyField(AssetGroup, blank=True, related_name='assets', verbose_name=_('Asset groups')) admin_user = models.ForeignKey(AdminUser, null=True, blank=True, related_name='assets', on_delete=models.SET_NULL, verbose_name=_("Admin user")) system_users = models.ManyToManyField(SystemUser, blank=True, related_name='assets', verbose_name=_("System User")) - idc = models.ForeignKey(IDC, blank=True, null=True, related_name='assets', on_delete=models.SET_NULL, verbose_name=_('IDC'),) + cluster = models.ForeignKey(Cluster, blank=True, null=True, related_name='assets', on_delete=models.SET_NULL, verbose_name=_('Cluster'),) is_active = models.BooleanField(default=True, verbose_name=_('Is active')) type = models.CharField(choices=TYPE_CHOICES, max_length=16, blank=True, null=True, default='Server', verbose_name=_('Asset type'),) env = models.CharField(choices=ENV_CHOICES, max_length=8, blank=True, null=True, default='Prod', verbose_name=_('Asset environment'),) @@ -100,18 +100,16 @@ class Asset(models.Model): 'hostname': self.hostname, 'ip': self.ip, 'port': self.port, + 'groups': [group.name for group in self.groups.all()], } def _to_secret_json(self): - """Ansible use it create inventory""" - data = { - 'id': self.id, - 'hostname': self.hostname, - 'ip': self.ip, - 'port': self.port, - 'groups': [group.name for group in self.groups.all()], - } + """ + Ansible use it create inventory + Todo: May be move to ops implements it + """ + data = self.to_json() if self.admin_user: data.update({ 'username': self.admin_user.username, @@ -139,7 +137,7 @@ class Asset(models.Model): asset = cls(ip='%s.%s.%s.%s' % (i, i, i, i), hostname=forgery_py.internet.user_name(True), admin_user=choice(AdminUser.objects.all()), - idc=choice(IDC.objects.all()), + cluster=choice(Cluster.objects.all()), port=22, created_by='Fake') try: diff --git a/apps/assets/models/cluster.py b/apps/assets/models/cluster.py new file mode 100644 index 000000000..54ce1be4e --- /dev/null +++ b/apps/assets/models/cluster.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# + +from __future__ import unicode_literals + +import logging +import uuid + +from django.db import models +from django.utils.translation import ugettext_lazy as _ + + +__all__ = ['Cluster'] +logger = logging.getLogger(__name__) + + +class Cluster(models.Model): + id = models.UUIDField(default=uuid.uuid4, primary_key=True) + name = models.CharField(max_length=32, verbose_name=_('Name')) + bandwidth = models.CharField(max_length=32, blank=True, verbose_name=_('Bandwidth')) + contact = models.CharField(max_length=128, blank=True, verbose_name=_('Contact')) + phone = models.CharField(max_length=32, blank=True, verbose_name=_('Phone')) + address = models.CharField(max_length=128, blank=True, verbose_name=_("Address")) + intranet = models.TextField(blank=True, verbose_name=_('Intranet')) + extranet = models.TextField(blank=True, verbose_name=_('Extranet')) + date_created = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('Date created')) + operator = models.CharField(max_length=32, blank=True, verbose_name=_('Operator')) + created_by = models.CharField(max_length=32, blank=True, verbose_name=_('Created by')) + comment = models.TextField(blank=True, verbose_name=_('Comment')) + + def __str__(self): + return self.name + + @classmethod + def initial(cls): + return cls.objects.get_or_create(name=_('Default'), created_by=_('System'), comment=_('Default Cluster'))[0] + + class Meta: + ordering = ['name'] + + @classmethod + def generate_fake(cls, count=5): + from random import seed, choice + import forgery_py + from django.db import IntegrityError + + seed() + for i in range(count): + cluster = cls(name=forgery_py.name.full_name(), + bandwidth='200M', + contact=forgery_py.name.full_name(), + phone=forgery_py.address.phone(), + address=forgery_py.address.city() + forgery_py.address.street_address(), + operator=choice(['北京联通', '北京电信', 'BGP全网通']), + comment=forgery_py.lorem_ipsum.sentence(), + created_by='Fake') + try: + cluster.save() + logger.debug('Generate fake asset group: %s' % cluster.name) + except IntegrityError: + print('Error continue') + continue diff --git a/apps/assets/models/idc.py b/apps/assets/models/idc.py deleted file mode 100644 index 97a39b25d..000000000 --- a/apps/assets/models/idc.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# - -from __future__ import unicode_literals - -import logging -import uuid - -from django.db import models -from django.utils.translation import ugettext_lazy as _ - - -__all__ = ['IDC'] -logger = logging.getLogger(__name__) - - -class IDC(models.Model): - id = models.UUIDField(default=uuid.uuid4, primary_key=True) - name = models.CharField(max_length=32, verbose_name=_('Name')) - bandwidth = models.CharField( - max_length=32, blank=True, verbose_name=_('Bandwidth')) - contact = models.CharField( - max_length=128, blank=True, verbose_name=_('Contact')) - phone = models.CharField(max_length=32, blank=True, - verbose_name=_('Phone')) - address = models.CharField( - max_length=128, blank=True, verbose_name=_("Address")) - intranet = models.TextField(blank=True, verbose_name=_('Intranet')) - extranet = models.TextField(blank=True, verbose_name=_('Extranet')) - date_created = models.DateTimeField( - auto_now_add=True, null=True, verbose_name=_('Date created')) - operator = models.CharField( - max_length=32, blank=True, verbose_name=_('Operator')) - created_by = models.CharField( - max_length=32, blank=True, verbose_name=_('Created by')) - comment = models.TextField(blank=True, verbose_name=_('Comment')) - - def __unicode__(self): - return self.name - __str__ = __unicode__ - - @classmethod - def initial(cls): - return cls.objects.get_or_create(name=_('Default'), created_by=_('System'), comment=_('Default IDC'))[0] - - class Meta: - ordering = ['name'] - - @classmethod - def generate_fake(cls, count=5): - from random import seed, choice - import forgery_py - from django.db import IntegrityError - - seed() - for i in range(count): - idc = cls(name=forgery_py.name.full_name(), - bandwidth='200M', - contact=forgery_py.name.full_name(), - phone=forgery_py.address.phone(), - address=forgery_py.address.city() + forgery_py.address.street_address(), - operator=choice(['北京联通', '北京电信', 'BGP全网通']), - comment=forgery_py.lorem_ipsum.sentence(), - created_by='Fake') - try: - idc.save() - logger.debug('Generate fake asset group: %s' % idc.name) - except IntegrityError: - print('Error continue') - continue diff --git a/apps/assets/models/user.py b/apps/assets/models/user.py index 7cb5f83ba..5b2388cf0 100644 --- a/apps/assets/models/user.py +++ b/apps/assets/models/user.py @@ -29,7 +29,7 @@ def private_key_validator(value): class AdminUser(models.Model): """ - Ansible use admin user as devops user to run adHoc and Playbook + A privileged user that ansible can use it to push system user and so on """ BECOME_METHOD_CHOICES = ( ('sudo', 'sudo'), @@ -43,7 +43,7 @@ class AdminUser(models.Model): become = models.BooleanField(default=True) become_method = models.CharField(choices=BECOME_METHOD_CHOICES, default='sudo', max_length=4) become_user = models.CharField(default='root', max_length=64) - become_pass = models.CharField(default='', max_length=128) + _become_pass = models.CharField(default='', max_length=128) _public_key = models.TextField(max_length=4096, blank=True, verbose_name=_('SSH public key')) comment = models.TextField(blank=True, verbose_name=_('Comment')) date_created = models.DateTimeField(auto_now_add=True, null=True) @@ -95,6 +95,15 @@ class AdminUser(models.Model): def public_key(self, public_key_raw): self._public_key = signer.sign(public_key_raw) + @property + def become_pass(self): + return signer.unsign(self._become_pass) + + @become_pass.setter + def become_pass(self, password): + self._become_pass = signer.sign(password) + + @property def assets_amount(self): return self.assets.count() diff --git a/apps/assets/models/utils.py b/apps/assets/models/utils.py index b6c2d2ae6..8b1c94502 100644 --- a/apps/assets/models/utils.py +++ b/apps/assets/models/utils.py @@ -2,19 +2,19 @@ # -*- coding: utf-8 -*- # -from . import IDC, SystemUser, AdminUser, AssetGroup, Asset +from . import Cluster, SystemUser, AdminUser, AssetGroup, Asset __all__ = ['init_model', 'generate_fake'] def init_model(): - for cls in [IDC, SystemUser, AdminUser, AssetGroup, Asset]: + for cls in [Cluster, SystemUser, AdminUser, AssetGroup, Asset]: if hasattr(cls, 'initial'): cls.initial() def generate_fake(): - for cls in [IDC, SystemUser, AdminUser, AssetGroup, Asset]: + for cls in [Cluster, SystemUser, AdminUser, AssetGroup, Asset]: if hasattr(cls, 'generate_fake'): cls.generate_fake() diff --git a/apps/assets/serializers.py b/apps/assets/serializers.py index def2577c8..5a41cc386 100644 --- a/apps/assets/serializers.py +++ b/apps/assets/serializers.py @@ -2,7 +2,7 @@ from django.utils.translation import ugettext_lazy as _ from django.core.cache import cache from rest_framework import viewsets, serializers, generics -from .models import AssetGroup, Asset, IDC, AdminUser, SystemUser +from .models import AssetGroup, Asset, Cluster, AdminUser, SystemUser from common.mixins import IDInFilterMixin from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin @@ -54,11 +54,11 @@ class AssetGroupUpdateSystemUserSerializer(serializers.ModelSerializer): fields = ['id', 'system_users'] -class IDCUpdateAssetsSerializer(serializers.ModelSerializer): +class ClusterUpdateAssetsSerializer(serializers.ModelSerializer): assets = serializers.PrimaryKeyRelatedField(many=True, queryset=Asset.objects.all()) class Meta: - model = IDC + model = Cluster fields = ['id', 'assets'] @@ -180,12 +180,12 @@ class MyAssetGrantedSerializer(AssetGrantedSerializer): "is_active", "system_users_join", "comment") -class IDCSerializer(BulkSerializerMixin, serializers.ModelSerializer): +class ClusterSerializer(BulkSerializerMixin, serializers.ModelSerializer): assets_amount = serializers.SerializerMethodField() assets = serializers.PrimaryKeyRelatedField(many=True, queryset=Asset.objects.all()) class Meta: - model = IDC + model = Cluster fields = '__all__' @staticmethod @@ -193,7 +193,7 @@ class IDCSerializer(BulkSerializerMixin, serializers.ModelSerializer): return obj.assets.count() def get_field_names(self, declared_fields, info): - fields = super(IDCSerializer, self).get_field_names(declared_fields, info) + fields = super(ClusterSerializer, self).get_field_names(declared_fields, info) fields.append('assets_amount') return fields diff --git a/apps/assets/templates/assets/asset_create.html b/apps/assets/templates/assets/asset_create.html index 66ab350ee..fa6830a47 100644 --- a/apps/assets/templates/assets/asset_create.html +++ b/apps/assets/templates/assets/asset_create.html @@ -21,7 +21,7 @@
@@ -80,7 +80,7 @@
- {% trans 'Add assets to' %} {{ idc.name }}
+ {% trans 'Add assets to' %} {{ cluster.name }}
|
---|