Ejemplo n.º 1
0
    def executeGet(self):
        """
        Request:
            (...)/istsos/wa/istsos/<service name>/status/?type=delay

        The response is:
        >>>
        [
            {
                "name": "air-rainfall",
                "children": [
                    {
                        "name": "ok",
                        "children": [
                            {}
                        ]
                    },
                    {
                        "name": "pending",
                        "children": [
                            {
                                "delay": 35243.204681,
                                "lastObservation": "2014-05-12T07:00:00+0200",
                                "code": [
                                    2
                                ],
                                "name": "LOCARNO",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "status": "pending",
                                        "process": "acquisition",
                                        "datetime": "2014-05-12 09:00:00+02:00",
                                        "details": null,
                                        "message": "TypeError",
                                        "element": "LOCARNO",
                                        "id": 2
                                    }
                                ],
                                "lastMeasure": "2.000000",
                                "cycle": 4.894889539027778
                            },
                            {
                                "delay": 540143.269259,
                                "lastObservation": "2014-05-06T10:45:00+0200",
                                "code": [
                                    1,
                                    2,
                                    3
                                ],
                                "name": "P_LUGANO",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "details": "No exception found"
                                    }
                                ],
                                "lastMeasure": "32.000000",
                                "cycle": 75.01989850819444
                            }
                        ]
                    },
                    {
                        "name": "verified",
                        "children": [
                            {
                                "delay": 49163.155455,
                                "lastObservation": "2014-05-12T03:08:00+0200",
                                "code": [
                                    1,
                                    2,
                                    3
                                ],
                                "name": "BELLINZONA",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "status": "verified",
                                        "process": "acquisition",
                                        "datetime": "2014-05-12 05:00:00+02:00",
                                        "details": null,
                                        "message": "TypeError",
                                        "element": "BELLINZONA",
                                        "id": 1
                                    }
                                ],
                                "lastMeasure": "1.000000",
                                "type": "verified",
                                "cycle": 13.656432070833333
                            }
                        ]
                    }
                ]
            },
            {
                "name": "air-temperature",
                "children":[...]
            }
        ]
        """

        if self.service == "default":
            raise Exception("Status operation can not be done for default service instance.")

        servicedb = databaseManager.PgDB(
            self.serviceconf.connection['user'],
            self.serviceconf.connection['password'],
            self.serviceconf.connection['dbname'],
            self.serviceconf.connection['host'],
            self.serviceconf.connection['port'])

        #param = self.waEnviron['parameters']['type'][0]

        procedureData = []
        lastValue = {'values': 'No observation', 'uom': 'No observation'}
        for procedure in utils.getProcedureNamesList(servicedb, self.service):

            #if param == 'delay':
            status = self.__delay(procedure['name'], servicedb)
            if status is None:
                continue
            #else:
                #raise Exception("Operation %s not permitted." % (param))

            if(status['status'] == 'NOT OK'):
                # Require last exceptions
                logEnviron = self.waEnviron.copy()
                logEnviron['parameters'] = {}
                from walib.istsos.services.logs import logs
                log = logs.waLogs(logEnviron)

                logEnviron['parameters'] = {'element': [procedure['name']],
                                        'stime': [status['lastObservation']]}

                log.executeGet()

            if(status['lastObservation'] != 'No observation'):
                # Convert last Observation to string
                status['lastObservation'] = status['lastObservation'].strftime("%Y-%m-%dT%H:%M:%S%z")
                lastValue = self.__getLastObservation(servicedb,procedure['name'])

            procedureData.append(
                {
                    "procedure": procedure['name'],
                    "status": status,
                    "lastMeasure": lastValue,
                    "exception": log.response['data']
                }
            )

        jsonResult = []
        for op in utils.getObsPropNamesList(servicedb, self.service):
            propOk = []
            propNotOk = []
            propVerif = []
            for procedure in procedureData:
                if self.__containsOp(procedure, op['name']):
                    lastValue = self.__getLastValue(procedure, op['name'])
                    jsonProc = {
                                    "name": procedure['procedure'],
                                    "lastObservation": procedure['status']['lastObservation'],
                                    "lastMeasure": lastValue['values'],
                                    "oum": lastValue['uom'],
                                    "delay": procedure['status']['delay'],
                                    "cycle": procedure['status']['cycle']
                                }
                    if procedure['status']['status'] == "OK":
                        jsonProc['type'] = 'ok'
                        propOk.append(jsonProc)

                    elif procedure['status']['status'] == "NOT OK":
                        code = []
                        if procedure['exception']:
                            for exc in procedure['exception']:
                                if exc['message'] in getErrorCode:
                                    code.append(getErrorCode[exc['message']])
                                else:
                                    code.append(0)

                            jsonProc['code'] = code
                            jsonProc['exceptions'] = procedure['exception']

                            if(self.__checkError(procedure['exception'])):
                                propNotOk.append(jsonProc)
                            else:
                                jsonProc['type'] = 'verified'
                                propVerif.append(jsonProc)
                        else:
                            jsonProc['exceptions'] = [{"details": "No exceptions found"}]
                            propNotOk.append(jsonProc)

            if(len(propOk) == 0):
                propOk.append({})
            if(len(propNotOk) == 0):
                propNotOk.append({})
            if(len(propVerif) == 0):
                propVerif.append({})

            jsonResult.append({
                "name": op['name'],
                "children": [
                    {"name": "ok", "children": propOk},
                    {"name":"pending", "children": propNotOk},
                    {"name": "verified", "children": propVerif}
                ]
                }
            )

        self.setMessage("Status result")
        self.setData(jsonResult)
Ejemplo n.º 2
0
    def executeGet(self):
        """
        Request:
            (...)/istsos/wa/istsos/<service name>/status/?type=delay

        The response is:
        >>>
        [
            {
                "name": "air-rainfall",
                "children": [
                    {
                        "name": "ok",
                        "children": [
                            {}
                        ]
                    },
                    {
                        "name": "pending",
                        "children": [
                            {
                                "delay": 35243.204681,
                                "lastObservation": "2014-05-12T07:00:00+0200",
                                "code": [
                                    2
                                ],
                                "name": "LOCARNO",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "status": "pending",
                                        "process": "acquisition",
                                        "datetime": "2014-05-12 09:00:00+02:00",
                                        "details": null,
                                        "message": "TypeError",
                                        "element": "LOCARNO",
                                        "id": 2
                                    }
                                ],
                                "lastMeasure": "2.000000",
                                "cycle": 4.894889539027778
                            },
                            {
                                "delay": 540143.269259,
                                "lastObservation": "2014-05-06T10:45:00+0200",
                                "code": [
                                    1,
                                    2,
                                    3
                                ],
                                "name": "P_LUGANO",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "details": "No exception found"
                                    }
                                ],
                                "lastMeasure": "32.000000",
                                "cycle": 75.01989850819444
                            }
                        ]
                    },
                    {
                        "name": "verified",
                        "children": [
                            {
                                "delay": 49163.155455,
                                "lastObservation": "2014-05-12T03:08:00+0200",
                                "code": [
                                    1,
                                    2,
                                    3
                                ],
                                "name": "BELLINZONA",
                                "oum": "mm",
                                "exceptions": [
                                    {
                                        "status": "verified",
                                        "process": "acquisition",
                                        "datetime": "2014-05-12 05:00:00+02:00",
                                        "details": null,
                                        "message": "TypeError",
                                        "element": "BELLINZONA",
                                        "id": 1
                                    }
                                ],
                                "lastMeasure": "1.000000",
                                "type": "verified",
                                "cycle": 13.656432070833333
                            }
                        ]
                    }
                ]
            },
            {
                "name": "air-temperature",
                "children":[...]
            }
        ]
        """

        if self.service == "default":
            raise Exception(
                "Status operation can not be done for default service instance."
            )

        servicedb = databaseManager.PgDB(
            self.serviceconf.connection['user'],
            self.serviceconf.connection['password'],
            self.serviceconf.connection['dbname'],
            self.serviceconf.connection['host'],
            self.serviceconf.connection['port'])

        #param = self.waEnviron['parameters']['type'][0]

        procedureData = []
        lastValue = {'values': 'No observation', 'uom': 'No observation'}
        for procedure in utils.getProcedureNamesList(servicedb, self.service):
            log_res = []
            #if param == 'delay':
            status = self.__delay(procedure['name'], servicedb)
            if status is None:
                continue
            #else:
            #raise Exception("Operation %s not permitted." % (param))
            #print procedure['name']
            #print status['status']
            if (status['status'] == 'NOT OK'):
                # Require last exceptions
                logEnviron = self.waEnviron.copy()
                logEnviron['parameters'] = {}
                from walib.istsos.services.logs import logs
                log = logs.waLogs(logEnviron)

                logEnviron['parameters'] = {
                    'element': [procedure['name']],
                    'stime': [status['lastObservation']]
                }

                log.executeGet()

                #print log.response['data']

                log_res = log.response['data']

            if (status['lastObservation'] != 'No observation'):
                # Convert last Observation to string
                status['lastObservation'] = status['lastObservation'].strftime(
                    "%Y-%m-%dT%H:%M:%S%z")
                lastValue = self.__getLastObservation(servicedb,
                                                      procedure['name'])

            procedureData.append({
                "procedure": procedure['name'],
                "status": status,
                "lastMeasure": lastValue,
                "exception": log_res  #log.response['data']
            })

        jsonResult = []
        for op in utils.getObsPropNamesList(servicedb, self.service):
            propOk = []
            propNotOk = []
            propVerif = []
            for procedure in procedureData:
                if self.__containsOp(procedure, op['name']):
                    lastValue = self.__getLastValue(procedure, op['name'])
                    jsonProc = {
                        "name": procedure['procedure'],
                        "lastObservation":
                        procedure['status']['lastObservation'],
                        "lastMeasure": lastValue['values'],
                        "oum": lastValue['uom'],
                        "delay": procedure['status']['delay'],
                        "cycle": procedure['status']['cycle']
                    }
                    if procedure['status']['status'] == "OK":
                        jsonProc['type'] = 'ok'
                        propOk.append(jsonProc)

                    elif procedure['status']['status'] == "NOT OK":
                        code = []
                        if procedure['exception']:
                            for exc in procedure['exception']:
                                if exc['message'] in getErrorCode:
                                    code.append(getErrorCode[exc['message']])
                                else:
                                    code.append(0)

                            jsonProc['code'] = code
                            jsonProc['exceptions'] = procedure['exception']

                            if (self.__checkError(procedure['exception'])):
                                propNotOk.append(jsonProc)
                            else:
                                jsonProc['type'] = 'verified'
                                propVerif.append(jsonProc)
                        else:
                            jsonProc['exceptions'] = [{
                                "details":
                                "No exceptions found"
                            }]
                            propNotOk.append(jsonProc)

            if (len(propOk) == 0):
                propOk.append({})
            if (len(propNotOk) == 0):
                propNotOk.append({})
            if (len(propVerif) == 0):
                propVerif.append({})

            jsonResult.append({
                "name":
                op['name'],
                "children": [{
                    "name": "ok",
                    "children": propOk
                }, {
                    "name": "pending",
                    "children": propNotOk
                }, {
                    "name": "verified",
                    "children": propVerif
                }]
            })

        self.setMessage("Status result")
        self.setData(jsonResult)
Ejemplo n.º 3
0
    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")
Ejemplo n.º 4
0
 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&section=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")