Commit 80829ebb by Karsa Zoltán István

create instances via rest and add disk

parent bf49a963
from rest_framework.renderers import JSONRenderer
from rest_framework import serializers
from vm.models import InstanceTemplate, Lease
from vm.models import Instance, InstanceTemplate, Lease, Interface
from firewall.models import Vlan
from storage.models import Disk
......@@ -23,4 +24,34 @@ class DiskSerializer(serializers.ModelSerializer):
class Meta:
model = Disk
fields = ['id', 'name', 'filename', 'datastore', 'type', 'bus', 'size', 'base',
'dev_num', 'destroyed', 'ci_disk', 'is_ready']
\ No newline at end of file
'dev_num', 'destroyed', 'ci_disk', 'is_ready']
class InstanceSerializer(serializers.ModelSerializer):
ipv4addr = serializers.SerializerMethodField('get_ipv4')
ipv6addr = serializers.SerializerMethodField('get_ipv6')
def get_ipv4(self, i):
return str(i.ipv4)
def get_ipv6(self, i):
return str(i.ipv6)
class Meta:
model = Instance
fields = ['id', 'name', 'description', 'status', 'owner', 'access_method', 'boot_menu', 'pw', 'is_base',
'lease', 'raw_data', 'cloud_init', 'ci_meta_data', 'ci_user_data', 'system', 'req_traits',
'has_agent', 'num_cores', 'ram_size', 'max_ram_size', 'arch', 'priority', 'disks', 'node', 'ipv4addr', 'ipv6addr']
extra_kwargs = {'disks': {'required': False}}
class InterfaceSerializer(serializers.ModelSerializer):
class Meta:
model = Interface
fields = ['id', 'vlan', 'host', 'instance', 'model']
class VlanSerializer(serializers.ModelSerializer):
class Meta:
model = Vlan
fields = ['id', 'vid', 'name', 'description', 'comment', 'domain']
\ No newline at end of file
......@@ -54,21 +54,22 @@ from .views import (
TransferTemplateOwnershipView, TransferTemplateOwnershipConfirmView,
OpenSearchDescriptionView,
NodeActivityView,
UserList, TemplateREST, LeaseREST, DiskRest,
UserList, TemplateREST, LeaseREST, DiskRest, InstanceREST, InterfaceREST,
StorageDetail, DiskDetail,
MessageList, MessageDetail, MessageCreate, MessageDelete,
EnableTwoFactorView, DisableTwoFactorView,
AclUserGroupAutocomplete, AclUserAutocomplete,
RescheduleView, GroupImportView, GroupExportView, iac_vm_list
RescheduleView, GroupImportView, GroupExportView,
)
from .views.node import node_ops
from .views.vm import vm_ops, vm_mass_ops
urlpatterns = [
path('acpi/vm/', iac_vm_list),
path('acpi/vm/', InstanceREST.as_view()),
path('acpi/template/', TemplateREST.as_view()),
path('acpi/lease/', LeaseREST.as_view()),
path('acpi/disk/', DiskRest.as_view()),
path('acpi/interface/', InterfaceREST.as_view()),
url(r'^$', IndexView.as_view(), name="dashboard.index"),
url(r"^profile/list/$", UserList.as_view(),
name="dashboard.views.user-list"),
......
......@@ -74,7 +74,7 @@ from ..forms import (
from django.views.generic.edit import FormMixin
from request.models import TemplateAccessType, LeaseType
from request.forms import LeaseRequestForm, TemplateRequestForm
from ..models import Favourite
from ..models import Favourite, pwgen
from manager.scheduler import has_traits
......@@ -88,40 +88,64 @@ logger = logging.getLogger(__name__)
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.authentication import TokenAuthentication, BasicAuthentication
from rest_framework.permissions import IsAdminUser
@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAdminUser])
def iac_vm_list(request):
instances = Instance.objects.all()
instances = [{
'pk': i.pk,
'url': reverse('dashboard.views.detail', args=[i.pk]),
'name': i.name,
'host': i.short_hostname,
'status': i.get_status_display(),
'owner': (i.owner.profile.get_display_name()),
'node': i.node,
'timesuspend': i.time_of_suspend,
'timedelete': i.time_of_delete,
'timedestroy': i.destroyed_at,
'userdata': i.get_user_data,
'metadata': i.get_meta_data,
'template': i.template.pk if i.template else None,
'users': list({ 'username': u.username, 'level': l } for u, l in i.get_users_with_level()),
} for i in instances]
return Response(instances)
@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAdminUser])
def iac_vm_create(request):
return Response()
from dashboard.serializers import InstanceSerializer, InterfaceSerializer
class InterfaceREST(APIView):
authentication_classes = [TokenAuthentication,BasicAuthentication]
permission_classes = [IsAdminUser]
def get(self, request, format=None):
templates = Interface.objects.all()
serializer = InterfaceSerializer(templates, many=True)
return JsonResponse({ 'interfaces': serializer.data}, safe=False)
class InstanceREST(APIView):
authentication_classes = [TokenAuthentication,BasicAuthentication]
permission_classes = [IsAdminUser]
def get(self, request, format=None):
templates = Instance.objects.all()
serializer = InstanceSerializer(templates, many=True)
return JsonResponse({ 'instances': serializer.data}, safe=False)
def post(self, request, format=None):
data = JSONParser().parse(request)
data['pw'] = pwgen()
data['status'] = 'STOPPED'
serializer = InstanceSerializer(data=data)
if serializer.is_valid():
inst = serializer.save()
networks = []
for v in data['vlans']:
v = Vlan.objects.filter(vid=v).get()
if not v.has_level(request.user, "user"):
raise PermissionDenied()
networks.append(InterfaceTemplate(vlan=v, managed=v.managed))
def __on_commit(activity):
activity.resultant_state = 'PENDING'
with inst.activity(code_suffix='create',
readable_name=ugettext_noop("create instance (REST)"),
on_commit=__on_commit, user=inst.owner) as act:
for net in networks:
Interface.create(instance=inst, vlan=net.vlan,
owner=inst.owner, managed=net.managed,
base_activity=act)
if 'create_disk' in data:
inst.create_disk(size=data['createdisk']['size'], user=inst.owner,
name=data['createdisk']['name'], activity=None)
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
class VmDetailVncTokenView(CheckedDetailView):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment