added login ticket cache

This commit is contained in:
Miłosz Stocki 2019-12-12 12:11:49 +01:00
parent 0b5ccbb102
commit 9b97de7cd6
Signed by: osiu97
GPG Key ID: E3D1D83FA04F51D6
1 changed files with 42 additions and 2 deletions

View File

@ -5,7 +5,9 @@ import json
from VM import VM from VM import VM
from Node import Node from Node import Node
from Storage import Storage from Storage import Storage
import time
CACHEFILE='/tmp/zabbix_ticket.json'
def get_auth(host, username, password): def get_auth(host, username, password):
""" """
@ -37,8 +39,46 @@ class PVEApi(object):
""" """
self.host = host self.host = host
self.url = "https://" + self.host + "/api2/json" self.url = "https://" + self.host + "/api2/json"
self.csrftoken = get_auth(self.host, username, password)[0] if self.check_cacheexpire():
self.ticket = get_auth(self.host, username, password)[1] 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): def get_request(self, url):
""" """