Django vCenter Server REST APIs проверяет, не отключен ли Vcsa

Я создал приложение на django 2.2, которое взаимодействует с REST API vCenter Server. На нем я могу делать различные запросы.

На vCenter у меня есть два ESX сервера 10.122.151.60 и 10.122.151.50, где есть несколько виртуальных машин.

Я могу общаться с ними через мое приложение django. Проблема в том, что когда первый сервер не отвечает, мое приложение не понимает, и поэтому второй тоже не работает. Запросы не проходят, потому что первый сервер не отвечает.

Я создал функцию, которая проверяет все Vcsa и отправляет письмо, если один из Vcsa не отвечает. Проблема в том, что если первый сервер не работает, а второй работает, то функция покажет мне только статус одного работающего сервера, но не другого.

Не знаю, понятно ли я выразился, но внимательно прочитайте комментарии и импорт каждого файла.

# vm.py
from vmware.views.tools import check_vcsa_status

def vm_vcsa_chech_status(request):
"""
A function used to generate a response message about the state
of one or several Vcsa and send an email afterwards.
:param request:Contains information about current user.
:return:Returns a Http response with 1 argument:
    1.'mylist' Contains a list of the Vcsa and the error message.
    Ex : Vcsa1 : ConnectTimeoutError.
"""
vcsa = Vmware.objects.all()
mylist, mylistvcsa = list(), list()
vcsa_status = str()
for i in vcsa:
    # problem here, it's doesn't check the first server down
    if check_vcsa_status(i.pk) != 200:
        vcsa_status += f'<tr><td>{i.hostname}</td>' \
                  f'<td>{check_vcsa_status(i.pk)}</td></tr>'
        mylistvcsa.append(i.hostname)
        mylistvcsa.append(check_vcsa_status(i.pk))
        mylist.append(mylistvcsa)
        mylistvcsa = list()
    else:
        return HttpResponse(check_vcsa_status(i.pk))
msg = EmailMessage("Vcsa status",
                   "<html><head><style> .table_list {border-collapse: "
                   "collapse;margin: 20px 0 0 "
                   "30px;min-width:400px;max-width:700px;width: "
                   "auto;background: #3e4551}  .table_list thead th {"
                   "border-top: none;vertical-align: bottom;"
                   "border-bottom: 2px solid #CED4DA;}.table_list td, "
                   ".table_list th {border-top: 1px solid #CED4DA;"
                   "border-bottom: 1px solid #92989B;padding: 8px;"
                   "color: #F8F9FA}  .table_list th {padding: 8px;"
                   "color: #F8F9FA;}  .table_list td {color: "
                   "#F8F9FA;}</style></head><body><h1>MYAPI</h1>"
                   "<table class='table_list'><thead><tr>"
                   "<th>Vcsa Name(s)</th><th>Error Message(s)</th>"
                   "</tr></thead><tbody>"
                   + vcsa_status + "</tbody></table>"
                   "</body""></html>",
                   "titi@gmail.com",
                   ["toto@gmail.com"])
msg.content_subtype = "html"
msg.send()
return HttpResponse(mylist)

tools.py

from vmware.views.api import VmwareApi
def check_vcsa_status(pk):
"""
A function used to get the version of the Vcsa using GET request
method to the server.
:param pk:Primary key of item used in queryset.
:return:If the Vcsa version is lower than the actuel version
on the server, use different argument and fetch the status code from
the GET response request. Else change argument and fetch the status
code from the GET response request. Return the 'status code' if
success, else a custom error message. If the GET request method fail
an exeception is raise.
"""
myvcsa = Vmware.objects.get(pk=pk)
vmreq = VmwareApi()
vmreq.ip = myvcsa.ip
vmreq.user = myvcsa.username
vmreq.password = myvcsa.password
ses = vmreq.session()
if ses == 'ConnectTimeoutError':
    return 'ConnectTimeoutError'
vmreq.arg1 = '/rest/appliance/system/version'
try:
    req1 = vmreq.vapirequestget()
    if req1 == 'ConnectTimeoutError':
        return 'ConnectTimeoutError'
    else:
        if req1.status_code == 200:
            return req1.status_code
        elif req1.status_code == 401 or req1.status_code == 500:
            if 'value' in req1.json():
                if 'messages' in req1.json()['value']:
                    return req1.json()['value']['messages'][0][
                            'default_message']
            else:
                return req1.json()['messages'][0]['default_message']
        else:
            return req1.status_code
except Exception as e:
    return e    

api.py

class VmwareApi:
def __init__(self):
    self.ip = ""
    self.user = ""
    self.password = ""
    self.arg1 = ""
    self.ses = ""
    self.params = ""
    
    
def session(self):
    try:
        a = req.post('https://' + self.ip + '/api/session',
                     auth=(self.user, self.password),
                     timeout=1, verify=False)
        self.ses = str(a.json())
    except requests.exceptions.Timeout:
        return 'ConnectTimeoutError'
    return req

def param_loader(self):
    if self.params:
        self.params = json.loads(self.params)

def vapirequestget(self):
    try:
        VmwareApi.param_loader(self)
        myreq = req.get('https://' + self.ip + self.arg1,
                        params=self.params, verify=False,
                        headers={"vmware-api-session-id": self.ses},
                        timeout=1)
        return myreq
    except requests.exceptions.Timeout:
        return 'ConnectTimeoutError'
Вернуться на верх