def __init__(self, waEnviron, service=None, loadjson=True): waResourceAdmin.__init__(self, waEnviron, loadjson) if service is None: i = self.pathinfo.index("services") if i > 0 and i < len(self.pathinfo) - 1: self.service = self.pathinfo[i + 1] else: self.service = None else: self.service = service self.checkAuthorization() #set default config path if not os.path.isdir(self.waconf.paths["services"]): raise Exception( "servicespath is not configured in the wa.cfg file [%s]." % self.waconf.paths["services"]) defaultCFGpath = os.path.join(self.waconf.paths["services"], "default.cfg") if not os.path.isfile(defaultCFGpath): raise Exception( "istsos [default] configuration file not found in %s." % (defaultCFGpath)) if not (self.service is None or self.service == 'default'): serviceCFGpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "%s.cfg" % self.service) if not os.path.isfile(serviceCFGpath): raise ServiceNotFound( "istsos [%s] configuration file not found in %s." % (self.service, serviceCFGpath), self.service) self.servicepath = os.path.join(self.waconf.paths["services"], "%s" % self.service) sensormlpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "sml") if not os.path.isdir(sensormlpath): raise Exception( "istsos [%s] sensorML folder not found in %s." % (self.service, sensormlpath)) self.sensormlpath = sensormlpath virtualpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "virtual") if not os.path.isdir(virtualpath): raise Exception( "istsos [%s] virtual procedures folder not found in %s." % (self.service, virtualpath)) self.virtualpath = virtualpath if self.service == None or self.service == 'default': self.serviceconf = configManager.waServiceConfig(defaultCFGpath) else: self.serviceconf = configManager.waServiceConfig( defaultCFGpath, serviceCFGpath)
def __init__(self): """ """ defaultCFGpath = path.join( path.dirname(path.split(path.abspath(__file__))[0]), "services/default.cfg") self.serviceconf = configManager.waServiceConfig(defaultCFGpath) now = datetime.datetime.now().replace(tzinfo=timezone(time.tzname[0])) self.__setDate(now)
def __init__(self, waEnviron, service=None, loadjson=True): waResourceAdmin.__init__(self, waEnviron, loadjson) if service == None: i = self.pathinfo.index("services") if i > 0 and i < len(self.pathinfo) - 1: self.service = self.pathinfo[i + 1] else: self.service = None else: self.service = service # set default config path if not os.path.isdir(self.waconf.paths["services"]): raise Exception("servicespath is not configured in the wa.cfg file [%s]." % self.waconf.paths["services"]) defaultCFGpath = os.path.join(self.waconf.paths["services"], "default.cfg") if not os.path.isfile(defaultCFGpath): raise Exception("istsos [default] configuration file not found in %s." % (defaultCFGpath)) if not (self.service == None or self.service == "default"): serviceCFGpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "%s.cfg" % self.service) if not os.path.isfile(serviceCFGpath): raise Exception("istsos [%s] configuration file not found in %s." % (self.service, serviceCFGpath)) self.servicepath = os.path.join(self.waconf.paths["services"], "%s" % self.service) sensormlpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "sml") if not os.path.isdir(sensormlpath): raise Exception("istsos [%s] sensorML folder not found in %s." % (self.service, sensormlpath)) self.sensormlpath = sensormlpath virtualpath = os.path.join(self.waconf.paths["services"], "%s" % self.service, "virtual") if not os.path.isdir(virtualpath): raise Exception("istsos [%s] virtual procedures folder not found in %s." % (self.service, virtualpath)) self.virtualpath = virtualpath if self.service == None or self.service == "default": self.serviceconf = configManager.waServiceConfig(defaultCFGpath) else: self.serviceconf = configManager.waServiceConfig(defaultCFGpath, serviceCFGpath)
def __init__(self, conf=None): """ Initialize the MQTTMediator class conf """ self.lock = threading.Lock() self.conf = conf self.broker = {} self.services = {} defaultCfg = os.path.join(config.services_path, "default.cfg") instances = utils.getServiceList(config.services_path, listonly=False) for instance in instances: sc = configManager.waServiceConfig(defaultCfg, instance['path']) conn = databaseManager.PgDB(sc.connection["user"], sc.connection["password"], sc.connection["dbname"], sc.connection["host"], sc.connection["port"]) self.services[instance['service']] = {"config": sc, "conn": conn} # Get mqtt configurations rows = conn.select(""" SELECT id_prc, mqtt_prc, name_prc FROM %s.procedures""" % (instance['service'])) for row in rows: if row[1] is not None and row[1] != '': mqttConf = json.loads(row[1]) if 'broker_port' in mqttConf and ( mqttConf['broker_port'] is not None and mqttConf['broker_port'] != ''): broker_url = "%s:%s" % (mqttConf['broker_url'], mqttConf['broker_port']) else: broker_url = "%s:1883" % (mqttConf['broker_url']) topic = mqttConf['broker_topic'] if broker_url not in self.broker: self.broker[broker_url] = {} self.broker[broker_url][topic] = { "id": row[0], "name": row[2], "instance": instance['service'] }
def __init__(self, wnsEnviron, loadjson=True): """ Initialize resource object @param wnsEnviron: wnsEnviron variable see L(wa) @type wnsEnviron: C{dictionary} """ self.response = { "success": True, "message": "" } self.wnsEnviron = wnsEnviron self.method = wnsEnviron['method'] self.pathinfo = wnsEnviron['pathinfo'] self.json = None self.postRequest = None if self.method in ["POST", "PUT"] and loadjson: import json self.json = ut.encodeobject(json.loads(wnsEnviron['wsgi_input'])) defaultCFGpath = os.path.join(wnsEnviron["services_path"], "default.cfg") self.serviceconf = configManager.waServiceConfig(defaultCFGpath)
def __init__(self, wnsEnviron, loadjson=True): """ Initialize resource object parameters: wnsEnviron (dict): wnsEnviron variable see L(wa) """ self.response = { "success": True, "message": "" } self.wnsEnviron = wnsEnviron self.method = wnsEnviron['method'] self.pathinfo = wnsEnviron['pathinfo'] self.json = None self.postRequest = None if self.method in ["POST", "PUT"] and loadjson: import json self.json = ut.encodeobject(json.loads(wnsEnviron['wsgi_input'])) defaultCFGpath = os.path.join(wnsEnviron["services_path"], "default.cfg") self.serviceconf = configManager.waServiceConfig(defaultCFGpath)
def executeGet(self): try: os.path.isdir(self.waconf.paths["istsos"]) except: error = "istsos lib not found at path %s" % self.waconf.paths["istsos"] print >> sys.stderr, error try: os.path.isdir(self.waconf.paths["services"]) except: error = "services lib not found at path %s" % self.waconf.paths["services"] print >> sys.stderr, error defaultcfgpath = os.path.join(self.waconf.paths["services"],"default.cfg") try: os.path.isfile(defaultcfgpath) except: error = "default service configuration file at path %s" % defaultcfgpath print >> sys.stderr, error config = configManager.waServiceConfig(defaultcfgpath) self.setData({"level" : config.initialization["level"]}) if int(config.initialization["level"]) == 0: self.setMessage("Your istsos has not been initializated jet") else: self.setMessage("Your istsos has been initializated")
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #=============================================================================== from os import path from walib import configManager import os import sys import config defaultCFGpath = path.join(config.services_path, "default.cfg") serviceconf = configManager.waServiceConfig(defaultCFGpath) services_path = path.join(config.wns_path, "notifications.aps") wns_script_path = path.join(config.wns_path, "scripts") def delNotification(name): """Delete selected notification remove notification from notification.aps, data-base and remove the function file Args: name (str): Name of the notification """ aps_file = open(services_path, 'r')
def executeGet(self): """ Execute GET request investigating set-up services @note: This method creates a C{self.data} object in the form of a list of dictionaries as below: >>> template = { "service" : None, "offerings" : None, "procedures" : None, "observedProperties" : None, "featuresOfInterest" : None, "getCapabilities" : None, "describeSensor" : None, "getObservations" : None, "registerSensor" : None, "insertObservation" : None, "getFeatureOfInterest" : None, "availability" : "up" } """ services = utils.getServiceList( self.waconf.paths["services"], listonly=True) if self.user and not self.user.isAdmin(): servicesAllowed = [] for item in services: if self.user.allowedService(item): servicesAllowed.append(item) services = servicesAllowed data = [] for service in services: srv = {} srv["service"] = service # get service configuration defaultcfgpath = os.path.join( self.waconf.paths["services"], "default.cfg") servicecfgpath = "%s.cfg" % os.path.join( self.waconf.paths["services"], service, service) config = configManager.waServiceConfig( defaultcfgpath, servicecfgpath) # test if service is active (check answer to GetCapabilities) if config.serviceurl["default"] is True: urlget = config.serviceurl["url"] + "/" + service else: urlget = config.serviceurl["url"] request = ("?request=getCapabilities&" "section=serviceidentification&service=SOS") srv["availability"] = utils.verifyxmlservice( urlget+request, self.waEnviron) # test if connection is valid connection = config.get("connection") try: servicedb = databaseManager.PgDB( connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port'] ) srv["database"] = "active" except: srv["database"] = "not connectable" srv["offerings"] = None srv["procedures"] = None srv["observedProperties"] = None srv["featuresOfInterest"] = None try: #count offerings srv["offerings"] = len( utils.getOfferingNamesList(servicedb, service)) except: srv["offerings"] = None try: #count procedures srv["procedures"] = len( utils.getProcedureNamesList( servicedb, service, offering=None)) except: srv["procedures"] = None try: #count observed properties srv["observedProperties"] = len( utils.getObsPropNamesList( servicedb, service, offering=None)) except: srv["observedProperties"] = None try: #count features of interest srv["featuresOfInterest"] = len( utils.getFoiNamesList(servicedb, service, offering=None)) except: srv["featuresOfInterest"] = None #get available requests requests_ON = config.parameters["requests"].split(",") for operation in [ "getcapabilities", "describesensor", "getobservation", "getfeatureofinterest", "insertobservation", "registersensor"]: if operation in requests_ON: srv[operation] = True else: srv[operation] = False data.append(srv) self.setData(data) self.setMessage("Serverstatus request successfully executed")
def executeGet(self): """ Method for executing a GET requests that rename a SOS service .. note:: This method renames: 1. service folder, 2. service configuration file 3. the databse schema The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check to be at service level without serviceID provided in url if self.urlservicename is None: try: serviceslist = utils.getServiceList( self.waEnviron["services_path"], listonly=False) if self.user and not self.user.isAdmin(): servicesAllowed = [] for item in serviceslist: if self.user.allowedService(item['service']): servicesAllowed.append(item) serviceslist = servicesAllowed except Exception as ex: print >> sys.stderr, traceback.print_exc() raise ex self.setData(serviceslist) self.setMessage( "Services list successfully retrived: found [%s] services" % (len(serviceslist))) else: try: serviceslist = utils.getServiceList( self.waEnviron["services_path"], listonly=True) if not (self.urlservicename in serviceslist): raise Exception("") except Exception as ex: print >> sys.stderr, traceback.print_exc() raise ex #get database connection and initialize it defaultcfgpath = os.path.join(self.waEnviron["services_path"], "default.cfg") servicecfgpath = "%s.cfg" % os.path.join( self.waEnviron["services_path"], self.urlservicename, self.urlservicename) config = configManager.waServiceConfig(defaultcfgpath, servicecfgpath) connection = config.get("connection") #test if connection is valid servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port']) self.setData({ "service": self.urlservicename, "user": connection['user'], #"password" : connection['password'], "password": "******", "dbname": connection['dbname'], "host": connection['host'], "port": connection['port'] }) self.setMessage( "Informations of service <%s> successfully retrived" % (self.urlservicename))
def executePost(self,db=True): """ Method for executing a POST requests that initialize a new SOS service .. note:: This method creates: 1. service folder, 2. service configuration file 3. C{sensorML} folder 4. C{virtual procedures} folder 5. a new schema with the same name of your service 6. istSOS tables and relations in the new schema The POST must be in Json format with mandatory service key, if databease keys are not provided the server default connection are used: >>> { "service" : "service_name", "user" : "pinco" "password" : "pallino" "dbname" : "sos_db" "host" : "10.7.5.3" "port" : "5432" } """ #check to be at service level without serviceID provided in url if not self.urlservicename == None and db==True: raise Exception("POST action with url service name not supported") #check that service name was provided if not "service" in self.json: raise Exception("PUT action require the new service name sent within request body") #validate schemaname against injection utils.preventInjection(self.json["service"]) #validate db connection #------------------------------------- jsoncount = 0 dbkeys = ["user","password","dbname","host","port"] for key in dbkeys: if key in self.json : jsoncount += 1 defaultcfgpath = os.path.join(self.waEnviron["services_path"],"default.cfg") defaultconfig = configManager.waServiceConfig(defaultcfgpath) if jsoncount == 5: servicedb = databaseManager.PgDB( self.json["user"], self.json["password"], self.json["dbname"], self.json["host"], self.json["port"]) elif jsoncount == 0: defaultconnection = defaultconfig.get("connection") servicedb = databaseManager.PgDB( defaultconnection['user'], defaultconnection['password'], defaultconnection['dbname'], defaultconnection['host'], defaultconnection['port']) else: raise Exception("db parameters [service,user,password,dbname,host,port] must be all or none provided") #verify that the schema does not exist #------------------------------------- sql = "SELECT count(*) from pg_namespace WHERE nspname = %s" par = (self.json["service"],) res = servicedb.select(sql,par) if len(res)==1: pass else: raise Exception("a schema '%s' already exist" % self.json["service"]) #check if service folder does not exist: in case create it #------------------------------------------------------------------- newservicepath = os.path.join( self.waEnviron["services_path"],self.json["service"] ) try: os.makedirs(newservicepath) except OSError as exc: if exc.errno == errno.EEXIST: raise Exception("Service %s already exist" %(self.json["service"]) ) else: raise exc #create configuration file #------------------------------------------------------------------- configfile = os.path.join(self.waEnviron["services_path"],self.json["service"],self.json["service"])+".cfg" open(configfile, 'w').close() #--set EPSGdefault #create sensorML folder #------------------------------------------------------------------- smldir = os.path.join(self.waEnviron["services_path"],self.json["service"],"sml") os.makedirs(smldir) #create virtual procedure path #------------------------------------------------------------------- virtualdir = os.path.join(self.waEnviron["services_path"],self.json["service"],"virtual") os.makedirs(virtualdir) if db==True: try: #create schema #------------------------------------------------------------------- sql = "CREATE SCHEMA %s" % self.json["service"] servicedb.executeInTransaction(sql) #set db path #------------------------------------------------------------------- sql = "SET search_path = %s, public, pg_catalog" % self.json["service"] servicedb.executeInTransaction(sql,par) #create tableas and relations #------------------------------------------------------------------- from walib import sqlschema defaultepsg = defaultconfig.get("geo")['istsosepsg'] import sys if not "epsg" in self.json: sql = sqlschema.createsqlschema.replace("$SRID",defaultepsg).replace("$schema",self.json["service"]) else: sql = sqlschema.createsqlschema.replace("$SRID",self.json['epsg']) #set correct default EPSG of the new service #------------------------------------------------------------------- newconfig = configManager.waServiceConfig(defaultcfgpath,configfile) allowed = newconfig.get('geo')['allowedEPSG'].split(",") if self.json['epsg'] in allowed: newallowedepsg = ",".join([x for x in allowed if x != self.json['epsg']]) newconfig.put('geo','allowedEPSG',newallowedepsg) newconfig.save() newconfig.put('geo','istsosepsg',self.json['epsg']) newconfig.save() servicedb.executeInTransaction(sql) servicedb.commitTransaction() except: servicedb.rollbackTransaction() raise # Setting proxy configuration from walib.istsos.services.configsections import serviceurl surl = configManager.waServiceConfig(defaultcfgpath, configfile) url = '' if self.waEnviron['server_port'] == '80': url = 'http://' else: url = 'https://' url = "%s%s%s/%s" % (url, self.waEnviron['server_name'], self.waEnviron['script_name'], self.json["service"]) surl.put("serviceurl", "url", url) surl.save() self.setMessage( "New service <%s> correctly created" % str(self.json["service"]) )
def executePut(self): """ Method for executing a PUT requests that rename a SOS service .. note:: This method renames: 1. create a new service folder, 2. copy content from old to new service configuration file 3. rename the databse schema 4. delete old service files The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check to be at service level without serviceID provided in url #------------------------------------------------------------------- if self.urlservicename == None: raise Exception("PUT action with url service name not supported") #check that service name was provided #------------------------------------------------------------------- if not "service" in self.json: raise Exception("PUT action require the new service name sent within request body") #create a new service with new name #------------------------------------------------------------------- try: self.executePost(db=False) except: raise #copy configuration file to new configuration file name #------------------------------------------------------------------- try: defaultcfgpath = os.path.join(self.waEnviron["services_path"],"default.cfg") servicecfgpath = os.path.join(self.waEnviron["services_path"],self.urlservicename,self.urlservicename)+".cfg" newservicecfgpath = os.path.join(self.waEnviron["services_path"],self.json["service"],self.json["service"])+".cfg" of = open(servicecfgpath, "r") content = of.read() of.close() nf = open(newservicecfgpath, 'w') nf.write(content) nf.close() except: #remove new files shutil.rmtree(os.path.join(self.waEnviron["services_path"],self.json["service"])) raise Exception("cannot copy configuration file content") #rename database schema to new service name #------------------------------------------------------------------- try: config = configManager.waServiceConfig(defaultcfgpath,servicecfgpath) connection = config.get("connection") servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port'] ) sql = "ALTER SCHEMA %s RENAME TO %s" %(self.urlservicename,str(self.json["service"])) servicedb.executeInTransaction(sql) except: #remove new files shutil.rmtree(os.path.join(self.waEnviron["services_path"],self.json["service"])) raise #Exception("invalid alter schema sql") #remove service folder and subfolder contents #------------------------------------------------------------------- try: shutil.rmtree(os.path.join(self.waEnviron["services_path"],self.urlservicename)) except: servicedb.rollbackTransaction() servicedb.commitTransaction() self.setMessage("service <%s> successfully renamed to <%s>" %(self.urlservicename,str(self.json["service"])))
def executeDelete(self): """ Method for executing a DELETE requests that erase a SOS service .. note:: This method delete: 1. service folder, 2. service configuration file 3. C{sensorML} folder 4. C{virtual procedures} folder 5. a new schema with the same name of your service 6. istSOS tables and relations in the new schema The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check schemaname input if self.urlservicename == None: raise Exception("DELETE action without url service name not supported") #validate schemaname against injection utils.preventInjection(self.urlservicename) #get database connection and initialize it defaultcfgpath = os.path.join(self.waEnviron["services_path"],"default.cfg") servicepath = os.path.join(self.waEnviron["services_path"],self.urlservicename) servicecfgpath = os.path.join(self.waEnviron["services_path"],self.urlservicename,self.urlservicename)+".cfg" if not os.path.isdir(servicepath): raise Exception("service [%s] does not exists." % self.urlservicename) if not os.path.isdir(os.path.join(self.waEnviron["services_path"],self.urlservicename,"virtual")): raise Exception("service [%s] misconfigured, missing <virtual> folder." % self.urlservicename) if not os.path.isdir(os.path.join(self.waEnviron["services_path"],self.urlservicename,"sml")): raise Exception("service [%s] misconfigured, missing <sml> folder." % self.urlservicename) if not os.path.isfile(servicecfgpath): raise Exception("service [%s] misconfigured, missing config file." % self.urlservicename) config = configManager.waServiceConfig(defaultcfgpath,servicecfgpath) connection = config.get("connection") servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port'] ) #verify that the schema exist #------------------------------------- sql = "SELECT count(*) from pg_namespace WHERE nspname = %s" par = (self.urlservicename,) res = servicedb.select(sql,par) if len(res)==1: pass else: raise Exception("the db schema <<%s>> doesn't exist" % self.urlservicename) try: #drop schema #------------------------------------------------------------------- sql = "DROP SCHEMA %s CASCADE" % self.urlservicename servicedb.executeInTransaction(sql) #remove service folder and subfolder contents #------------------------------------------------------------------- shutil.rmtree(servicepath) servicedb.commitTransaction() except: servicedb.rollbackTransaction() raise self.setMessage("Service <%s> correctly deleted" % self.urlservicename)
def executeGet(self): """ Execute GET request investigating set-up services @note: This method creates a C{self.data} object in the form of a list of dictionaries as below: >>> template = {"service" : None, "offerings" : None, "procedures" : None, "observedProperties" : None, "featuresOfInterest" : None, "getCapabilities" : None, "describeSensor" : None, "getObservations" : None, "registerSensor" : None, "insertObservation" : None, "getFeatureOfInterest" : None, "availability" : "up" } """ services = utils.getServiceList(self.waconf.paths["services"],listonly=True) data = [] for service in services: srv = {} srv["service"] = service #get service configuration #------------------------------------------------------------------- defaultcfgpath = os.path.join(self.waconf.paths["services"],"default.cfg") servicecfgpath = os.path.join(self.waconf.paths["services"],service,service)+".cfg" config = configManager.waServiceConfig(defaultcfgpath,servicecfgpath) #test if service is active (check answer to GetCapabilities) #------------------------------------------------------------------- if config.serviceurl["default"] == True: urlget = config.serviceurl["url"] + "/" + service else: urlget = config.serviceurl["url"] request = "?request=getCapabilities§ion=serviceidentification&service=SOS" srv["availability"] = utils.verifyxmlservice(urlget+request) #test if connection is valid #------------------------------------------------------------------- connection = config.get("connection") try: servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port'] ) srv["database"] = "active" except: srv["database"] = "not connectable" srv["offerings"] = None srv["procedures"] = None srv["observedProperties"] = None srv["featuresOfInterest"] = None try: #count offerings #------------------------------------------------------------------- srv["offerings"] = len(utils.getOfferingNamesList(servicedb,service)) except: srv["offerings"] = None try: #count procedures #------------------------------------------------------------------- srv["procedures"] = len(utils.getProcedureNamesList(servicedb,service,offering=None)) except: srv["procedures"] = None try: #count observed properties #------------------------------------------------------------------- srv["observedProperties"] = len(utils.getObsPropNamesList(servicedb,service,offering=None)) except: srv["observedProperties"] = None try: #count features of interest #------------------------------------------------------------------- srv["featuresOfInterest"] = len(utils.getFoiNamesList(servicedb,service,offering=None)) except: srv["featuresOfInterest"] = None #get available requests #------------------------------------------------------------------- requests_ON = config.parameters["requests"].split(",") for operation in ["getcapabilities","describesensor","getobservation", "getfeatureofinterest","insertobservation","registersensor"]: if operation in requests_ON: srv[operation]=True else: srv[operation]=False data.append(srv) self.setData(data) self.setMessage("Serverstatus request successfully executed")
def executePut(self): defaultcfgpath = os.path.join(self.waconf.paths["services"],"default.cfg") config = configManager.waServiceConfig(defaultcfgpath) config.put("initialization","level",self.json["level"]) config.save() self.setMessage("Initializatuion level successfully recorded")
def executeDelete(self): """ Method for executing a DELETE requests that erase a SOS service .. note:: This method delete: 1. service folder, 2. service configuration file 3. C{sensorML} folder 4. C{virtual procedures} folder 5. a new schema with the same name of your service 6. istSOS tables and relations in the new schema The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check schemaname input if self.urlservicename is None: raise Exception("DELETE action without url service" "name not supported") #validate schemaname against injection utils.preventInjection(self.urlservicename) #get database connection and initialize it defaultcfgpath = os.path.join(self.waEnviron["services_path"], "default.cfg") servicepath = os.path.join(self.waEnviron["services_path"], self.urlservicename) servicecfgpath = "%s.cfg" % os.path.join( self.waEnviron["services_path"], self.urlservicename, self.urlservicename) if not os.path.isdir(servicepath): raise Exception("service [%s] does not exists." % self.urlservicename) if not os.path.isdir( os.path.join(self.waEnviron["services_path"], self.urlservicename, "virtual")): raise Exception( "service [%s] misconfigured, missing <virtual> folder." % (self.urlservicename)) if not os.path.isdir( os.path.join(self.waEnviron["services_path"], self.urlservicename, "sml")): raise Exception( "service [%s] misconfigured, missing <sml> folder." % (self.urlservicename)) if not os.path.isfile(servicecfgpath): raise Exception( "service [%s] misconfigured, missing config file." % (self.urlservicename)) config = configManager.waServiceConfig(defaultcfgpath, servicecfgpath) connection = config.get("connection") servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port']) #verify that the schema exist sql = "SELECT count(*) from pg_namespace WHERE nspname = %s" par = (self.urlservicename, ) res = servicedb.select(sql, par) if len(res) == 1: pass else: raise Exception("the db schema <<%s>> doesn't exist" % self.urlservicename) try: #drop schema sql = "DROP SCHEMA %s CASCADE" % self.urlservicename servicedb.executeInTransaction(sql) #remove service folder and subfolder contents shutil.rmtree(servicepath) servicedb.commitTransaction() except: servicedb.rollbackTransaction() raise self.setMessage("Service <%s> correctly deleted" % self.urlservicename)
def executePut(self): """ Method for executing a PUT requests that rename a SOS service .. note:: This method renames: 1. create a new service folder, 2. copy content from old to new service configuration file 3. rename the databse schema 4. delete old service files The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check to be at service level without serviceID provided in url if self.urlservicename is None: raise Exception("PUT action with url service name not supported") #check that service name was provided if not "service" in self.json: raise Exception( "PUT action require the new service name sent within " "request body") #create a new service with new name try: self.executePost(db=False) except: raise #copy configuration file to new configuration file name try: defaultcfgpath = os.path.join(self.waEnviron["services_path"], "default.cfg") servicecfgpath = "%s.cfg" % os.path.join( self.waEnviron["services_path"], self.urlservicename, self.urlservicename) newservicecfgpath = "%s.cfg" % os.path.join( self.waEnviron["services_path"], self.json["service"], self.json["service"]) of = open(servicecfgpath, "r") content = of.read() of.close() nf = open(newservicecfgpath, 'w') nf.write(content) nf.close() except: #remove new files shutil.rmtree( os.path.join(self.waEnviron["services_path"], self.json["service"])) raise Exception("cannot copy configuration file content") #rename database schema to new service name try: config = configManager.waServiceConfig(defaultcfgpath, servicecfgpath) connection = config.get("connection") servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port']) sql = "ALTER SCHEMA %s RENAME TO %s" % (self.urlservicename, str(self.json["service"])) servicedb.executeInTransaction(sql) except Exception as tex: #remove new files shutil.rmtree( os.path.join(self.waEnviron["services_path"], self.json["service"])) raise tex #remove service folder and subfolder contents try: shutil.rmtree( os.path.join(self.waEnviron["services_path"], self.urlservicename)) except: servicedb.rollbackTransaction() servicedb.commitTransaction() self.setMessage("service <%s> successfully renamed to <%s>" % (self.urlservicename, str(self.json["service"])))
def executeGet(self): """ Method for executing a GET requests that rename a SOS service .. note:: This method renames: 1. service folder, 2. service configuration file 3. the databse schema The POST must be in Json format with mandatory service key >>> { "service" : "service_name" } """ #check to be at service level without serviceID provided in url #------------------------------------------------------------------- if self.urlservicename == None: try: serviceslist = utils.getServiceList(self.waEnviron["services_path"],listonly=False) except Exception as ex: print >> sys.stderr, traceback.print_exc() raise ex self.setData(serviceslist) self.setMessage("Services list successfully retrived: found [%s] services" % len(serviceslist) ) else: try: serviceslist = utils.getServiceList(self.waEnviron["services_path"],listonly=True) if not(self.urlservicename in serviceslist): raise Exception("") except Exception as ex: print >> sys.stderr, traceback.print_exc() raise ex #get database connection and initialize it #------------------------------------------------------------------- defaultcfgpath = os.path.join(self.waEnviron["services_path"],"default.cfg") servicecfgpath = os.path.join(self.waEnviron["services_path"],self.urlservicename, self.urlservicename)+".cfg" config = configManager.waServiceConfig(defaultcfgpath,servicecfgpath) connection = config.get("connection") #test if connection is valid #------------------------------------------------------------------- servicedb = databaseManager.PgDB(connection['user'], connection['password'], connection['dbname'], connection['host'], connection['port'] ) self.setData({ "service": self.urlservicename, "user" : connection['user'], "password" : connection['password'], "dbname" : connection['dbname'], "host" : connection['host'], "port" : connection['port'] }) self.setMessage("Informations of service <%s> successfully retrived" % self.urlservicename)
def executePost(self, db=True): """Method for executing a POST requests that initialize a new SOS service .. note:: This method creates: 1. service folder, 2. service configuration file 3. C{sensorML} folder 4. C{virtual procedures} folder 5. a new schema with the same name of your service 6. istSOS tables and relations in the new schema The POST must be in Json format with mandatory service key, if databease keys are not provided the server default connection are used: >>> { "service" : "service_name", "user" : "pinco" "password" : "pallino" "dbname" : "sos_db" "host" : "10.7.5.3" "port" : "5432" } """ # check to be at service level without serviceID provided in url if not self.urlservicename is None and db is True: raise Exception("POST action with url service name not supported") # check that service name was provided if not "service" in self.json: raise Exception("PUT action require the new service" "name sent within request body") # validate schemaname against injection utils.preventInjection(self.json["service"]) # validate db connection jsoncount = 0 dbkeys = ["user", "password", "dbname", "host", "port"] for key in dbkeys: if key in self.json: jsoncount += 1 defaultcfgpath = os.path.join(self.waEnviron["services_path"], "default.cfg") defaultconfig = configManager.waServiceConfig(defaultcfgpath) if jsoncount == 5: servicedb = databaseManager.PgDB(self.json["user"], self.json["password"], self.json["dbname"], self.json["host"], self.json["port"]) elif jsoncount == 0: defaultconnection = defaultconfig.get("connection") servicedb = databaseManager.PgDB(defaultconnection['user'], defaultconnection['password'], defaultconnection['dbname'], defaultconnection['host'], defaultconnection['port']) else: raise Exception("db parameters [service, user, password, dbname, " "host, port] must be all or none provided") # verify that the schema does not exist sql = "SELECT count(*) from pg_namespace WHERE nspname = %s" par = (self.json["service"], ) res = servicedb.select(sql, par) if len(res) == 1: pass else: raise Exception("a schema '%s' already exist" % self.json["service"]) # check if service folder does not exist: in case create it newservicepath = os.path.join(self.waEnviron["services_path"], self.json["service"]) try: os.makedirs(newservicepath) except OSError as exc: if exc.errno == errno.EEXIST: raise Exception("Service %s already exist" % (self.json["service"])) else: raise exc # create configuration file configfile = "%s.cfg" % os.path.join(self.waEnviron["services_path"], self.json["service"], self.json["service"]) open(configfile, 'w').close() # create sensorML folder smldir = os.path.join(self.waEnviron["services_path"], self.json["service"], "sml") os.makedirs(smldir) # create virtual procedure path virtualdir = os.path.join(self.waEnviron["services_path"], self.json["service"], "virtual") os.makedirs(virtualdir) if db is True: try: #create schema sql = "CREATE SCHEMA %s" % self.json["service"] servicedb.executeInTransaction(sql) #set db path sql = "SET search_path = %s, public, pg_catalog" % ( self.json["service"]) servicedb.executeInTransaction(sql, par) #create tableas and relations from walib import sqlschema defaultepsg = defaultconfig.get("geo")['istsosepsg'] import sys if not "epsg" in self.json: sql = sqlschema.createsqlschema.replace( "$SRID", defaultepsg).replace("$schema", self.json["service"]) else: sql = sqlschema.createsqlschema.replace( "$SRID", self.json['epsg']) #set correct default EPSG of the new service newconfig = configManager.waServiceConfig( defaultcfgpath, configfile) allowed = newconfig.get('geo')['allowedEPSG'].split(",") if self.json['epsg'] in allowed: newallowedepsg = ",".join( [x for x in allowed if x != self.json['epsg']]) newconfig.put('geo', 'allowedEPSG', newallowedepsg) newconfig.save() newconfig.put('geo', 'istsosepsg', self.json['epsg']) newconfig.save() servicedb.executeInTransaction(sql) servicedb.commitTransaction() except: servicedb.rollbackTransaction() raise # Setting proxy configuration from walib.istsos.services.configsections import serviceurl surl = configManager.waServiceConfig(defaultcfgpath, configfile) url = '' if self.waEnviron['server_port'] == '80': url = 'http://' else: url = 'https://' url = "%s%s%s/%s" % (url, self.waEnviron['server_name'], self.waEnviron['script_name'], self.json["service"]) surl.put("serviceurl", "url", url) surl.save() self.setMessage("New service <%s> correctly created" % str(self.json["service"]))
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # =============================================================================== from os import path from walib import configManager defaultCFGpath = path.join(path.dirname(path.split(path.abspath(__file__))[0]), "services/default.cfg") serviceconf = configManager.waServiceConfig(defaultCFGpath) services_path = path.join(path.dirname(path.split(path.abspath(__file__))[0]), "services/notifications.aps") def delNotification(name): aps_file = open(services_path, 'r') data = aps_file.readlines() aps_file.close() x = 0 start = '### start ' + name + ' ###' end = '### end ' + name + ' ###' while not start in data[x]: