1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2024-12-27 08:35:22 +00:00
webvirtcloud/datasource/views.py

111 lines
2.6 KiB
Python
Raw Normal View History

2020-04-24 16:34:29 +00:00
import json
import socket
from accounts.models import UserInstance, UserSSHKey
from computes.models import Compute
2022-11-02 13:05:41 +00:00
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404, render
from libvirt import libvirtError
from vrtManager.instance import wvmInstance
2020-04-24 16:34:29 +00:00
OS_VERSIONS = ["latest", ""]
OS_UUID = "iid-dswebvirtcloud"
def os_index(request):
2020-04-24 16:34:29 +00:00
"""
:param request:
:return:
"""
response = "\n".join(OS_VERSIONS)
return HttpResponse(response)
def os_metadata_json(request, version):
"""
:param request:
:param version:
:return:
"""
if version == "latest":
ip = get_client_ip(request)
hostname = get_hostname_by_ip(ip)
response = {"uuid": OS_UUID, "hostname": hostname}
return HttpResponse(json.dumps(response))
else:
err = "Invalid version: %(version)s" % {"version": version}
raise Http404(err)
def os_userdata(request, version):
"""
:param request:
:param version:
:return:
"""
if version == "latest":
ip = get_client_ip(request)
hostname = get_hostname_by_ip(ip)
vname = hostname.split(".")[0]
2020-09-25 12:57:17 +00:00
instance_keys = []
userinstances = UserInstance.objects.filter(instance__name=vname)
2020-09-25 12:57:17 +00:00
for ui in userinstances:
keys = UserSSHKey.objects.filter(user=ui.user)
for k in keys:
instance_keys.append(k.keypublic)
return render(request, "user_data", locals())
else:
err = "Invalid version: %(version)s" % {"version": version}
raise Http404(err)
def get_client_ip(request):
2020-04-24 16:34:29 +00:00
"""
:param request:
:return:
"""
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[-1].strip()
else:
ip = request.META.get("REMOTE_ADDR")
return ip
def get_hostname_by_ip(ip):
2020-04-24 16:34:29 +00:00
"""
:param ip:
:return:
"""
try:
addrs = socket.gethostbyaddr(ip)
2019-09-10 06:48:31 +00:00
except:
addrs = [ip]
return addrs[0]
def get_vdi_url(request, compute_id, vname):
2020-04-24 16:34:29 +00:00
"""
:param request:
:param vname:
:return:
"""
compute = get_object_or_404(Compute, pk=compute_id)
2020-09-25 12:57:17 +00:00
try:
2022-11-02 05:54:35 +00:00
conn = wvmInstance(
2022-11-02 13:05:41 +00:00
compute.hostname, compute.login, compute.password, compute.type, vname
2022-11-02 05:54:35 +00:00
)
fqdn = get_hostname_by_ip(compute.hostname)
url = f"{conn.get_console_type()}://{fqdn}:{conn.get_console_port()}"
response = url
return HttpResponse(response)
2020-09-25 12:57:17 +00:00
except libvirtError:
err = "Error getting VDI URL for %(name)s" % {"name": vname}
raise Http404(err)