from trufimonitor import crypto, configValidator, events
import yaml, os, sys, threading

"""
Containing the resources Trufi Monitor needs
"""

class GlobalConfig:
	def __init__(self):
		self.trufimonitorStock = threading.Lock()
		self.configDir = "servers"
		
		self.fileLocation = os.path.join(self.configDir, "trufimonitor.yaml")
		self.active = {}
		self.default = {
	"dbconnection": { # database connection authentication details
		"host": "localhost",
		"port": 3306,
		"user": "root",
		"password": "<<PASSWORD>>",
		"database": "myDatabase"
	},
	"scheduler": {
		"host": "localhost",
		"port": 1234,
		"secret": crypto.Random.generate(100)
	},
	"maxPasswordGenerationLength": 500,
	"useUNIXSocket": False, # if True then use UNIX socket instead of the database connection string
	"runAsService": True, # a boolean indicating this should be run as a service
	"service": { # only takes effect when runAsService=True
		"checkingInterval": 900 # 60 seconds * 15 Minutes = 900 seconds (15 Minutes) to wait before checking the servers again
	},
	"checkSettings": { # Controls how Trufi Monitors spends the ressources on this machine to check all the servers
		"useOnlyThreads": False, # it should not spawn new processes and use threads instead
		"spawnProcesses": 10, # Spawn 10 processes. If useOnlyThreads=True then this will be ignored
		"threadsPerProcess": 1, # Threads per spawned process. 1 is Mininum (it is the main thread of the process which must exist) and numbers below 1 will be replaced by 1
		# spawnProcesses=10 and threadsPerProcess=10 means that 10*10 (10²) servers will be checked at the same time
	}
}
		self.active = self.default
		if not os.path.exists(self.fileLocation):
			print("File '{}' does not exist".format(self.fileLocation))
			if os.access(os.getcwd(), os.W_OK):
				print("  Creating it...")
				output = yaml.dump(self.active, default_flow_style=False)
				sfile = open(self.fileLocation, "w")
				sfile.write(output)
				sfile.close()
				print("  Creation successfull")
			else:
				print("  Cannot create it. Exiting...")
				print("EXPLANATION: File '{}' contains the configuration Trufi Monitor needs but that file does not exist and cannot be created. Please create that file yourself or give Trufi Monitor the necessary rights to do it theirself".format(self.fileLocation))
				sys.exit(10)
		
		print("registering reloading event for global configuration reload...")
		events.ProcessEvents.register_reloader(self.reloadTrufimonitorConfig) # register reloading event
		
		print("Trufi Monitor now listens to SIGHUB events so it can requested to reload its global configuration. Trigger reload process to complete initialization!")
		self.reloadTrufimonitorConfig()
		
	def reloadTrufimonitorConfig(self):
		print("loading new configuration...")
		sfile = open(self.fileLocation, "r")
		newConfig = yaml.safe_load(sfile.read())
		sfile.close()
		
		print("validating new configuration...")
		if configValidator.Validation(newConfig, configValidator.Template.trufimonitorYAML).noErrors:
			print("No validation errors found!")
			print("applying new configuration...")
			self.trufimonitorStock.acquire()
			self.active = self.default.copy() # RESETTING TO DEFAULT VALUES to prevent strange behaviours when changing the config fle twice or more while this program runs
			self.active.update(newConfig)
			self.trufimonitorStock.release()
			print("New configuration applied!")
		else:
			print("\033[0;31mThe new configuration contains errors so no new one has been applied!\033[0;m")

from trufimonitor import crypto, configValidator, events
import yaml, os, sys, threading

"""
Containing the resources Trufi Monitor needs
"""

class GlobalConfig:
	def __init__(self):
		self.trufimonitorStock = threading.Lock()
		self.configDir = "servers"
		
		self.fileLocation = os.path.join(self.configDir, "trufimonitor.yaml")
		self.active = {}
		self.default = {
	"dbconnection": { # database connection authentication details
		"host": "localhost",
		"port": 3306,
		"user": "root",
		"password": "<<PASSWORD>>",
		"database": "myDatabase"
	},
	"scheduler": {
		"host": "localhost",
		"port": 1234,
		"secret": crypto.Random.generate(100)
	},
	"maxPasswordGenerationLength": 500,
	"useUNIXSocket": False, # if True then use UNIX socket instead of the database connection string
	"runAsService": True, # a boolean indicating this should be run as a service
	"service": { # only takes effect when runAsService=True
		"checkingInterval": 900 # 60 seconds * 15 Minutes = 900 seconds (15 Minutes) to wait before checking the servers again
	},
	"checkSettings": { # Controls how Trufi Monitors spends the ressources on this machine to check all the servers
		"useOnlyThreads": False, # it should not spawn new processes and use threads instead
		"spawnProcesses": 10, # Spawn 10 processes. If useOnlyThreads=True then this will be ignored
		"threadsPerProcess": 1, # Threads per spawned process. 1 is Mininum (it is the main thread of the process which must exist) and numbers below 1 will be replaced by 1
		# spawnProcesses=10 and threadsPerProcess=10 means that 10*10 (10²) servers will be checked at the same time
	}
}
		self.active = self.default
		if not os.path.exists(self.fileLocation):
			print("File '{}' does not exist".format(self.fileLocation))
			if os.access(os.getcwd(), os.W_OK):
				print("  Creating it...")
				output = yaml.dump(self.active, default_flow_style=False)
				sfile = open(self.fileLocation, "w")
				sfile.write(output)
				sfile.close()
				print("  Creation successfull")
			else:
				print("  Cannot create it. Exiting...")
				print("EXPLANATION: File '{}' contains the configuration Trufi Monitor needs but that file does not exist and cannot be created. Please create that file yourself or give Trufi Monitor the necessary rights to do it theirself".format(self.fileLocation))
				sys.exit(10)
		
		print("registering reloading event for global configuration reload...")
		events.ProcessEvents.register_reloader(self.reloadTrufimonitorConfig) # register reloading event
		
		print("Trufi Monitor now listens to SIGHUB events so it can requested to reload its global configuration. Trigger reload process to complete initialization!")
		self.reloadTrufimonitorConfig()
		
	def reloadTrufimonitorConfig(self):
		print("loading new configuration...")
		sfile = open(self.fileLocation, "r")
		newConfig = yaml.safe_load(sfile.read())
		sfile.close()
		
		print("validating new configuration...")
		if configValidator.Validation(newConfig, configValidator.Template.trufimonitorYAML).noErrors:
			print("No validation errors found!")
			print("applying new configuration...")
			self.trufimonitorStock.acquire()
			self.active = self.default.copy() # RESETTING TO DEFAULT VALUES to prevent strange behaviours when changing the config fle twice or more while this program runs
			self.active.update(newConfig)
			self.trufimonitorStock.release()
			print("New configuration applied!")
		else:
			print("\033[0;31mThe new configuration contains errors so no new one has been applied!\033[0;m")

Containing the resources Trufi Monitor needs # database connection authentication details # if True then use UNIX socket instead of the database connection string # a boolean indicating this should be run as a service # only takes effect when runAsService=True # 60 seconds * 15 Minutes = 900 seconds (15 Minutes) to wait before checking the servers again # Controls how Trufi Monitors spends the ressources on this machine to check all the servers # it should not spawn new processes and use threads instead # Spawn 10 processes. If useOnlyThreads=True then this will be ignored # Threads per spawned process. 1 is Mininum (it is the main thread of the process which must exist) and numbers below 1 will be replaced by 1 # spawnProcesses=10 and threadsPerProcess=10 means that 10*10 (10²) servers will be checked at the same time # register reloading event # RESETTING TO DEFAULT VALUES to prevent strange behaviours when changing the config fle twice or more while this program runs