added login ticket cache
This commit is contained in:
parent
0b5ccbb102
commit
9b97de7cd6
44
PVEApi.py
44
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):
|
||||
"""
|
||||
|
|
|
|||
Loading…
Reference in New Issue