Commit 788d4f38 by Fukász Rómeó Ervin

core rendering, compute attributes, client csrf header

parent b72ff507
......@@ -9,7 +9,7 @@ import urllib3
# urllib3.disable_warnings()
# A szerver base url-je es a felhasznalo adatai
server = "https://vm.ik.bme.hu:15766/occi/"
server = "https://vm.ik.bme.hu:15766/"
username = "admin"
password = "retekretek"
loginData = {"username": username, "password": password}
......@@ -17,10 +17,21 @@ loginData = {"username": username, "password": password}
# Csinalunk egy sessiont, hogy a cookie ami az auth-ert felelos automatikusan benne
# maradjon az osszes keresunkben
with requests.Session() as session:
headers = {"Content-Type": "application/json", "Referer" : server}
try:
# Csrf-Token a bejelentkezeshez
req = session.get(server + "occi/login/", headers=headers, verify=False)
print("csrf-token")
print("----------")
print("status_code: " + str(req.status_code))
print(json.loads(req.text)["result"])
print
# Bejelentkezes
headers = {"Content-Type": "application/json"}
req = session.post(server + "login/", data=json.dumps(loginData),
# POST, DELETE, PUT keresek elott be kell allitani az X-CSRFToken header
# erteket az aktualis csrftoken-re, amely mindig benne van a cookie-ban
headers["X-CSRFToken"] = req.cookies['csrftoken']
req = session.post(server + "occi/login/", data=json.dumps(loginData),
headers=headers, verify=False)
print("login")
print("-----")
......@@ -35,7 +46,7 @@ with requests.Session() as session:
print
# Gep ebresztes teszt (meg nem OCCI)
req = session.get(server + "wakeup/", verify=False)
req = session.get(server + "occi/wakeup/", headers=headers, verify=False)
print("wakeup")
print("------")
print("status_code: " + str(req.status_code))
......@@ -43,7 +54,7 @@ with requests.Session() as session:
print
# Gep altatas teszt (meg nem OCCI)
req = session.get(server + "sleep/", verify=False)
req = session.get(server + "occi/sleep/", headers=headers, verify=False)
print("sleep")
print("-----")
print("status_code: " + str(req.status_code))
......@@ -51,7 +62,7 @@ with requests.Session() as session:
print
# Kijelentkezes
req = session.get(server + "logout/", verify=False)
req = session.get(server + "occi/logout/", headers=headers, verify=False)
print("logout")
print("------")
print("status_code: " + str(req.status_code))
......
......@@ -11,10 +11,6 @@ class Attribute:
optional_attributes = ("pattern", "default", "description")
pattern = None
default = None
description = None
def __init__(self, name, type, mutable, required, **kwargs):
self.name = name
self.type = type
......@@ -22,87 +18,170 @@ class Attribute:
self.required = required
set_optional_attributes(self, self.optional_attributes, kwargs)
def render_as_json(self):
json = {"mutable": self.mutable, "required": self.required,
"type": self.type}
if hasattr(self, "pattern"):
json["pattern"] = self.pattern
if hasattr(self, "default"):
json["default"] = self.default
if hasattr(self, "description"):
json["description"] = self.description
return json
class Category:
class Category(object):
""" OCCI 1.2 - CORE - Classification - Category """
optional_attributes = ("title", "attributes")
category_optional_attributes = ("title", "attributes")
title = None
attributes = ()
attributes = {}
def __init__(self, scheme, term, **kwargs):
self.scheme = scheme
self.term = term
set_optional_attributes(self, self.optional_attributes, kwargs)
set_optional_attributes(self, self.category_optional_attributes,
kwargs)
class Kind(Category):
""" OCCI 1.2 - CORE - Classification - Kind """
optional_attributes = ("parent", "actions", "enitities")
kind_optional_attributes = ("parent", "actions", "enitities")
parent = None
actions = ()
entities = ()
def __init__(self, **kwargs):
set_optional_attributes(self, self.optional_attributes, kwargs)
def __init__(self, *args, **kwargs):
super(Kind, self).__init__(*args, **kwargs)
set_optional_attributes(self, self.kind_optional_attributes,
kwargs)
def render_as_json(self):
json = {"term": self.term, "scheme": self.scheme,
"attributes": self.attributes, "actions": self.actions}
if hasattr(self, "title"):
json["title"] = self.title
if hasattr(self, "parent"):
json["parent"] = self.parent
if hasattr(self, "location"):
json["location"] = self.location
return json
class Action(Category):
""" OCCI 1.2 - CORE - Classification - Kind """
pass
""" OCCI 1.2 - CORE - Classification - Action """
def __init(self, *args, **kwargs):
super(Action, self).__init__(*args, **kwargs)
def render_as_json(self):
json = {"term": self.term, "scheme": self.scheme}
if hasattr(self, "title"):
json["title"] = self.title
if hasattr(self, "attributes"):
json["attributes"] = self.attributes
return json
class Mixin(Category):
""" OCCI 1.2 - CORE - Classification - Mixin """
optional_attributes = ("depends", "entities", "applies", "actions")
mixin_optional_attributes = ("depends", "entities", "applies",
"actions")
depends = ()
entities = ()
applies = ()
actions = ()
def __init__(self, **kwargs):
set_optional_attributes(self, self.optional_attributes, kwargs)
class Entity:
def __init__(self, *args, **kwargs):
super(Mixin, self).__init__(*args, **kwargs)
set_optional_attributes(self, self.mixin_optional_attributes,
kwargs)
def render_as_json(self):
json = {"term": self.term, "scheme": self.scheme,
"attributes": self.attributes, "actions": self.actions}
if hasattr(self, "title"):
json["title"] = self.title
if hasattr(self, "location"):
json["location"] = self.location
if hasattr(self, "depends"):
json["depends"] = self.depends
if hasattr(self, "applies"):
json["applies"] = self.applies
return json
class Entity(object):
""" OCCI 1.2 - CORE - Base Types - Entity """
optional_attributes = ("mixins", "title")
entity_optional_attributes = ("mixins", "title")
mixins = ()
title = None
def __init__(self, kind, id, **kwargs):
self.kind = kind
self.id = id
set_optional_attributes(self, self.optional_attributes, kwargs)
set_optional_attributes(self, self.entity_optional_attributes,
kwargs)
class Resource(Entity):
""" OCCI 1.2 - CORE - Base Types - Resource """
optional_attributes = ("links", "summary")
resource_optional_attributes = ("links", "summary")
links = ()
summary = None
def __init__(self, **kwargs):
set_optional_attributes(self, self.optional_attributes, kwargs)
def __init__(self, *args, **kwargs):
super(Resource, self).__init__(*args, **kwargs)
set_optional_attributes(self, self.resource_optional_attributes,
kwargs)
def render_as_json(self):
json = {"kind": self.kind, "id": self.id, "links": self.links,
"mixins": self.mixins}
if hasattr(self, "title"):
json["title"] = self.title
if hasattr(self, "summary"):
json["summary"] = self.summary
if hasattr(self, "attributes"):
json["attributes"] = self.attributes
if hasattr(self, "actions"):
json["actions"] = self.actions
return json
class Link(Entity):
""" OCCI 1.2 - CORE - Base Types - Link """
optional_attributes = ("target_kind",)
target_kind = None
link_optional_attributes = ("target.kind",)
def __init__(self, source, target, **kwargs):
def __init__(self, source, target, *args, **kwargs):
super(Link, self).__init__(*args, **kwargs)
self.source = source
self.target = target
set_optional_attributes(self, self.optional_attributes, kwargs)
set_optional_attributes(self, self.link_optional_attributes,
kwargs)
def render_as_json(self):
json = {"kind": self.kind, "id": self.id, "source" : self.source,
"target": self.target}
if hasattr(self, "mixins"):
json["mixins"] = self.mixins
if hasattr(self, "attributes"):
json["attributes"] = self.attributes
if hasattr(self, "actions"):
json["actions"] = self.actions
if hasattr(self, "title"):
json["title"] = self.title
return json
ENTITY_KIND = Kind("http://schemas.ogf.org/occi/core#", "entity",
title="Entity")
RESOURCE_KIND = Kind("http://schemas.ogf.org/occi/core#", "resource",
title="Resource",
parent="http://schemas.ogf.org/occi/core#entity")
""" Implementation of the OCCI - Infrastructure extension classes """
from occi_core import Resource
from occi_core import Action, Attribute, Resource
COMPUTE_ATTRIBUTES = [
Attribute("occi.compute.architecture", "Enum {x86, x84}", True, False,
description="CPU Architecture of the instance."),
Attribute("occi.compute.cores", "Integer", True, False,
description="Number of virtual CPU cores assigned to " +
"the instance."),
Attribute("occi.compute.hostname", "String", True, False,
description="Fully Qualified DNS hostname for the " +
"instance"),
Attribute("occi.compute.share", "Integer", True, False,
description="Relative number of CPU shares for the " +
"instance."),
Attribute("occi.compute.memory", "Float, 10^9 (GiB)", True, False,
description="Maximum RAM in gigabytes allocated to " +
"the instance."),
Attribute("occi.compute.state", "Enum {active, inactive, suspended, " +
"error}", False, True,
description="Current state of the instance."),
Attribute("occi.compute.state.message", "String", False, False,
description="Human-readable explanation of the current " +
"instance state"),
]
COMPUTE_ACTIONS = [
Action("http://schemas.ogf.org/occi/infrastructure/compute/action#",
"start", title="Start compute instance"),
Action("http://schemas.ogf.org/occi/infrastructure/compute/action#",
"stop", title="Stop compute instance",
attributes=[Attribute("method", "Enum {graceful, acpioff, " +
"poweroff}", True, False), ]),
Action("http://schemas.ogf.org/occi/infrastructure/compute/action#",
"restart", title="Restart compute instance",
attributes=[Attribute("method", "Enum {graceful, warm, cold}",
True, False), ]),
Action("http://schemas.ogf.org/occi/infrastructure/compute/action#",
"suspend", title="Suspend compute instance",
attributes=[Attribute("method", "Enum {hibernate, suspend}",
True, False), ]),
Action("http://schemas.ogf.org/occi/infrastructure/compute/action#",
"save", title="Create a template of compute instance",
attributes=[Attribute("method", "Enum {hot, deffered}", True,
False),
Attribute("name", "String", True, True), ]),
]
class Compute(Resource):
......
from django.conf.urls import url
from views import OcciLoginView, OcciLogoutView, WakeUpVM, SleepVM
from views import OcciLoginView, OcciLogoutView, TestView
urlpatterns = [
url(r'^login/$', OcciLoginView.as_view()),
url(r'^logout/$', OcciLogoutView.as_view()),
url(r'^wakeup/$', WakeUpVM.as_view()),
url(r'^sleep/$', SleepVM.as_view()),
url(r'^test/$', TestView.as_view()),
]
......@@ -9,14 +9,17 @@ from vm.models.instance import Instance
from common.models import HumanReadableException
from forms import OcciAuthForm
import json
from django.views.decorators.csrf import ensure_csrf_cookie
from django.utils.decorators import method_decorator
from occi_core import ENTITY_KIND
# TODO: csrf token
class OcciLoginView(View):
""" Authentication for the usage of the OCCI api.
This view responds with 200 and the access token in a Cookie if the
authentication succeeded, and with 400 if the provided username and
password is not valid. """
@method_decorator(ensure_csrf_cookie)
def get(self, request, *args, **kwargs):
""" Returns a response with a cookie to be used for requests other
than get. """
......@@ -45,34 +48,7 @@ class OcciLogoutView(View):
result = {"result": "OK"}
return JsonResponse(result)
class WakeUpVM(View):
""" A test service which gets a VM to wake up """
class TestView(View):
""" TEST VIEW """
def get(self, request, *args, **kwargs):
vm = Instance.objects.get(pk=6)
try:
vm.wake_up(user=request.user)
except HumanReadableException as e:
return HttpResponse(e.get_user_text(), status=400)
return HttpResponse("Virtual machine waked up")
class SleepVM(View):
""" A test service which gets a VM to sleep """
def get(self, request, *args, **kwargs):
vm = Instance.objects.get(pk=6)
try:
vm.sleep(user=request.user)
except HumanReadableException as e:
return HttpResponse(e.get_user_text(), status=400)
return HttpResponse("Virtual machine fell asleep")
class ComputeListView(View):
""" OCCI 1.2 - HTTP protocol - Collections - Compute """
def get(self, request, *args, **kwargs):
pass
class ComputeView(View):
pass
return JsonResponse(ENTITY_KIND.render_as_json())
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