new-openstackcheck-mk2/myOpenstackApp/OpenStackConnection.py

146 lines
5.3 KiB
Python

import requests
# import redis
import json
import os
from myOpenstackApp.logger import log
from myOpenstackApp import exceptions
class OpenStackConnection_x:
someProp=0
ks=False
nova=False
neutron=False
cinder=False
catalogData=""
novaURL=""
interface=""
token=""
"""
It's important not to initalise any of the submodules during the init cycle becuase thic causes cirtucalr import loops
The initalise function exists for this reas and should be caled by the client application using this module
"""
def __init__(self) -> None:
pass
def initalise(self) -> None:
log.info("Initalising connection")
from myOpenstackApp.keystone import myopenstack_keystone
from myOpenstackApp.nova import myopenstack_nova
from myOpenstackApp.neutron import myopenstack_neutron
from myOpenstackApp.cinder import myopenstack_cinder
self.ks=myopenstack_keystone(self)
self.nova=myopenstack_nova(self)
self.neutron=myopenstack_neutron(self)
self.cinder=myopenstack_cinder(self)
self.interface=os.getenv("OS_INTERFACE")
pass
def something(_self):
print(1)
_self.ks.getCatalog()
print(_self.nova.getAllServers(os.getenv("OS_PROJECT_ID"),True))
def make_request(_self, getPost, url, data, apiEndpoint, scopedProjectID=""):
log.debug("Making a request {} {} ".format(apiEndpoint,url))
# Default the scope project to the value set in .env.example, allow the user to override if required(EG creating backups)
if scopedProjectID== "":
if len(str(os.getenv("OS_PROJECT_ID")))<8:
raise Exception("No OS_PROJECT_ID provided")
scopedProjectID=os.getenv("OS_PROJECT_ID")
else:
scopedProjectID=scopedProjectID
str(url).replace(" ","%20")
data_json = json.dumps(data)
token = _self.getToken(os.getenv("OS_USERNAME"), os.getenv("OS_PASSWORD"),
os.getenv("OS_USER_DOMAIN_NAME"), os.getenv("OS_USER_DOMAIN_NAME"),
scopedProjectID)
# print (token)
headers = {'Content-type': 'application/json', 'X-Auth-Token': token}
url = apiEndpoint + "/" + url
if getPost=="GET":
response = requests.get(url, headers=headers,timeout=15)
elif getPost=="POST":
response = requests.post(url, data=data_json, headers=headers,timeout=15)
elif getPost=="DELETE":
response = requests.delete(url, headers=headers,timeout=15)
else:
raise ValueError("Unknown request type")
if 200<= response.status_code <= 300 :
return response
else:
raise ValueError ("Error in response return code" + str(response.status_code) + str(response.content))
def getToken(_self,username, password, authDomain, scopeDomain, scopeProject):
try:
return _self.lookupToken(username, authDomain, scopeDomain, scopeProject)
except exceptions.ItemNotFoundError:
url = os.getenv("OS_AUTH_URL") + '/auth/tokens'
xdata = {
"auth": {
"scope": {
"project": {
"domain": {
"name": scopeDomain
},
"id": scopeProject
}
},
"identity": {
"password": {
"user": {
"domain": {
"name": authDomain
},
"password": password,
"name": username
}
},
"methods": [
"password"
]
}
}
}
# response = requests.post(url)
headers = {'Content-type': 'application/json'}
response = requests.post(url, headers=headers,
data=json.dumps(xdata),
verify=False,
timeout=15)
if response.status_code == 201:
try:
_self.saveToken( username, authDomain, scopeDomain, scopeProject, response.headers['X-Subject-Token'])
except exceptions.ItemNotSavedError:
log.warn("Error saving token to redis..meh")
return response.headers['X-Subject-Token']
else:
raise ValueError("Error in token response to token request:"+response.text)
def lookupToken(_self, username, authDomain, scopeDomain, scopeProject):
if _self.token!="":
return _self.token
raise exceptions.ItemNotFoundError("OpenstackToken not found in redis")
def saveToken(_self, username, authDomain, scopeDomain, scopeProject,token):
_self.token=token
#raise exceptions.ItemNotSavedError("OpenstackToken not saved in redis")