From 9b97de7cd6d24e6f3ec02d44210a529320c00196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=82osz=20Stocki?= Date: Thu, 12 Dec 2019 12:11:49 +0100 Subject: [PATCH] added login ticket cache --- PVEApi.py | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/PVEApi.py b/PVEApi.py index 8575ea2..18b1ccc 100755 --- a/PVEApi.py +++ b/PVEApi.py @@ -5,7 +5,9 @@ import json from VM import VM from Node import Node from Storage import Storage +import time +CACHEFILE='/tmp/zabbix_ticket.json' def get_auth(host, username, password): """ @@ -37,8 +39,46 @@ class PVEApi(object): """ self.host = host self.url = "https://" + self.host + "/api2/json" - self.csrftoken = get_auth(self.host, username, password)[0] - self.ticket = get_auth(self.host, username, password)[1] + if self.check_cacheexpire(): + self.csrftoken = get_auth(self.host, username, password)[0] + self.ticket = get_auth(self.host, username, password)[1] + self.write_ticketcache() + else: + self.csrftoken = self.read_ticketcache()['csrf'] + self.ticket = self.read_ticketcache()['ticket'] + + def check_cacheexpire(self): + """ + Checks if API ticket is expired. + Proxmox says ticket is valid for 2 hours. For safety we use 1 hour + :return: Boolean value of True if ticket is considered expired. False if opposite. + """ + with open(CACHEFILE, 'r') as f: + data = json.load(f) + timestamp = data['timestamp'] + return True if time.time() - timestamp > 3600 else False + + + def write_ticketcache(self): + """ + Function writes API login ticket cache to tmp + """ + data = {} + data['csrf'] = self.csrftoken + data['ticket'] = self.ticket + data['timestamp'] = time.time() + with open(CACHEFILE, 'w') as f: + json.dump(data, f) + + def read_ticketcache(self): + """ + Reads API login ticket cache file + :return: returns json parsed dict + """ + with open(CACHEFILE, 'r') as f: + data = json.load(f) + return data + def get_request(self, url): """