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

core rendering, compute attributes, client csrf header

parent b72ff507
...@@ -9,7 +9,7 @@ import urllib3 ...@@ -9,7 +9,7 @@ import urllib3
# urllib3.disable_warnings() # urllib3.disable_warnings()
# A szerver base url-je es a felhasznalo adatai # 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" username = "admin"
password = "retekretek" password = "retekretek"
loginData = {"username": username, "password": password} loginData = {"username": username, "password": password}
...@@ -17,10 +17,21 @@ 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 # Csinalunk egy sessiont, hogy a cookie ami az auth-ert felelos automatikusan benne
# maradjon az osszes keresunkben # maradjon az osszes keresunkben
with requests.Session() as session: with requests.Session() as session:
headers = {"Content-Type": "application/json", "Referer" : server}
try: 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 # Bejelentkezes
headers = {"Content-Type": "application/json"} # POST, DELETE, PUT keresek elott be kell allitani az X-CSRFToken header
req = session.post(server + "login/", data=json.dumps(loginData), # 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) headers=headers, verify=False)
print("login") print("login")
print("-----") print("-----")
...@@ -35,7 +46,7 @@ with requests.Session() as session: ...@@ -35,7 +46,7 @@ with requests.Session() as session:
print print
# Gep ebresztes teszt (meg nem OCCI) # 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("wakeup")
print("------") print("------")
print("status_code: " + str(req.status_code)) print("status_code: " + str(req.status_code))
...@@ -43,7 +54,7 @@ with requests.Session() as session: ...@@ -43,7 +54,7 @@ with requests.Session() as session:
print print
# Gep altatas teszt (meg nem OCCI) # 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("sleep")
print("-----") print("-----")
print("status_code: " + str(req.status_code)) print("status_code: " + str(req.status_code))
...@@ -51,7 +62,7 @@ with requests.Session() as session: ...@@ -51,7 +62,7 @@ with requests.Session() as session:
print print
# Kijelentkezes # Kijelentkezes
req = session.get(server + "logout/", verify=False) req = session.get(server + "occi/logout/", headers=headers, verify=False)
print("logout") print("logout")
print("------") print("------")
print("status_code: " + str(req.status_code)) print("status_code: " + str(req.status_code))
......
...@@ -11,10 +11,6 @@ class Attribute: ...@@ -11,10 +11,6 @@ class Attribute:
optional_attributes = ("pattern", "default", "description") optional_attributes = ("pattern", "default", "description")
pattern = None
default = None
description = None
def __init__(self, name, type, mutable, required, **kwargs): def __init__(self, name, type, mutable, required, **kwargs):
self.name = name self.name = name
self.type = type self.type = type
...@@ -22,87 +18,170 @@ class Attribute: ...@@ -22,87 +18,170 @@ class Attribute:
self.required = required self.required = required
set_optional_attributes(self, self.optional_attributes, kwargs) 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 """ """ 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): def __init__(self, scheme, term, **kwargs):
self.scheme = scheme self.scheme = scheme
self.term = term self.term = term
set_optional_attributes(self, self.optional_attributes, kwargs) set_optional_attributes(self, self.category_optional_attributes,
kwargs)
class Kind(Category): class Kind(Category):
""" OCCI 1.2 - CORE - Classification - Kind """ """ OCCI 1.2 - CORE - Classification - Kind """
optional_attributes = ("parent", "actions", "enitities") kind_optional_attributes = ("parent", "actions", "enitities")
parent = None
actions = () actions = ()
entities = () entities = ()
def __init__(self, **kwargs): def __init__(self, *args, **kwargs):
set_optional_attributes(self, self.optional_attributes, 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): class Action(Category):
""" OCCI 1.2 - CORE - Classification - Kind """ """ OCCI 1.2 - CORE - Classification - Action """
pass 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): class Mixin(Category):
""" OCCI 1.2 - CORE - Classification - Mixin """ """ OCCI 1.2 - CORE - Classification - Mixin """
optional_attributes = ("depends", "entities", "applies", "actions") mixin_optional_attributes = ("depends", "entities", "applies",
"actions")
depends = () depends = ()
entities = () entities = ()
applies = () applies = ()
actions = () actions = ()
def __init__(self, **kwargs): def __init__(self, *args, **kwargs):
set_optional_attributes(self, self.optional_attributes, kwargs) super(Mixin, self).__init__(*args, **kwargs)
set_optional_attributes(self, self.mixin_optional_attributes,
kwargs)
class Entity:
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 """ """ OCCI 1.2 - CORE - Base Types - Entity """
optional_attributes = ("mixins", "title") entity_optional_attributes = ("mixins", "title")
mixins = () mixins = ()
title = None
def __init__(self, kind, id, **kwargs): def __init__(self, kind, id, **kwargs):
self.kind = kind self.kind = kind
self.id = id self.id = id
set_optional_attributes(self, self.optional_attributes, kwargs) set_optional_attributes(self, self.entity_optional_attributes,
kwargs)
class Resource(Entity): class Resource(Entity):
""" OCCI 1.2 - CORE - Base Types - Resource """ """ OCCI 1.2 - CORE - Base Types - Resource """
optional_attributes = ("links", "summary") resource_optional_attributes = ("links", "summary")
links = () links = ()
summary = None
def __init__(self, **kwargs): def __init__(self, *args, **kwargs):
set_optional_attributes(self, self.optional_attributes, 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): class Link(Entity):
""" OCCI 1.2 - CORE - Base Types - Link """ """ OCCI 1.2 - CORE - Base Types - Link """
optional_attributes = ("target_kind",) link_optional_attributes = ("target.kind",)
target_kind = None
def __init__(self, source, target, **kwargs): def __init__(self, source, target, *args, **kwargs):
super(Link, self).__init__(*args, **kwargs)
self.source = source self.source = source
self.target = target 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 """ """ 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): class Compute(Resource):
......
from django.conf.urls import url from django.conf.urls import url
from views import OcciLoginView, OcciLogoutView, WakeUpVM, SleepVM from views import OcciLoginView, OcciLogoutView, TestView
urlpatterns = [ urlpatterns = [
url(r'^login/$', OcciLoginView.as_view()), url(r'^login/$', OcciLoginView.as_view()),
url(r'^logout/$', OcciLogoutView.as_view()), url(r'^logout/$', OcciLogoutView.as_view()),
url(r'^wakeup/$', WakeUpVM.as_view()), url(r'^test/$', TestView.as_view()),
url(r'^sleep/$', SleepVM.as_view()),
] ]
...@@ -9,14 +9,17 @@ from vm.models.instance import Instance ...@@ -9,14 +9,17 @@ from vm.models.instance import Instance
from common.models import HumanReadableException from common.models import HumanReadableException
from forms import OcciAuthForm from forms import OcciAuthForm
import json 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): class OcciLoginView(View):
""" Authentication for the usage of the OCCI api. """ Authentication for the usage of the OCCI api.
This view responds with 200 and the access token in a Cookie if the This view responds with 200 and the access token in a Cookie if the
authentication succeeded, and with 400 if the provided username and authentication succeeded, and with 400 if the provided username and
password is not valid. """ password is not valid. """
@method_decorator(ensure_csrf_cookie)
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
""" Returns a response with a cookie to be used for requests other """ Returns a response with a cookie to be used for requests other
than get. """ than get. """
...@@ -45,34 +48,7 @@ class OcciLogoutView(View): ...@@ -45,34 +48,7 @@ class OcciLogoutView(View):
result = {"result": "OK"} result = {"result": "OK"}
return JsonResponse(result) return JsonResponse(result)
class TestView(View):
class WakeUpVM(View): """ TEST VIEW """
""" A test service which gets a VM to wake up """
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
vm = Instance.objects.get(pk=6) return JsonResponse(ENTITY_KIND.render_as_json())
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
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