Пример #1
0
    def _mdp_reply_plugin_stop(self, data):
        """ Stop the plugin
            @param data : MQ req message

            First, send the MQ Rep to 'ack' the request
            Then, change the plugin status to STATUS_STOP_REQUEST
            Then, quit the plugin by calling force_leave(). This should make the plugin send a STATUS_STOPPED if all is ok

            Notice that no check is done on the MQ req content : we need nothing in it as it is directly addressed to a plugin
        """
        # check if the message is for us
        content = data.get_data()
        if content['name'] != self._name or content['host'] != self.get_sanitized_hostname():
            return

        ### Send the ack over MQ Rep
        msg = MQMessage()
        msg.set_action('plugin.stop.result')
        status = True
        reason = ""
        msg.add_data('status', status)
        msg.add_data('reason', reason)
        self.reply(msg.get())

        ### Change the plugin status
        self._set_status(STATUS_STOP_REQUEST)

        ### Try to stop the plugin
        # if it fails, the manager should try to kill the plugin
        self.force_leave()
Пример #2
0
def delete_configuration(type, name, host):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.delete')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
        data = result.get_data()
        if 'status' in data:
            if not data['status']:
                print(result.get())
                raise RuntimeError(
                    "DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}"
                    .format(type, name, host, key, value))
            else:
                return True
        else:
            print(result.get())
            raise RuntimeError(
                "DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}"
                .format(type, name, host, key, value))
    else:
        raise RuntimeError(
            "Timeout while deleting configuration for {0}-{1}.{2}".format(
                type, name, host))
Пример #3
0
    def _mdp_reply_plugin_start(self, data):
        """ Reply on the MQ
            @param data : msg REQ received
        """
        msg = MQMessage()
        msg.set_action('plugin.start.result')

        if 'name' not in data.get_data().keys():
            status = False
            reason = "Plugin startup request : missing 'name' field"
            self.log.error(reason)
        else:
            name = data.get_data()['name']
            msg.add_data('name', name)

            # try to start the plugin
            pid = self._plugins[name].start()
            if pid != 0:
                status = True
                reason = ""
            else:
                status = False
                reason = "Plugin '{0}' startup failed".format(name)

        msg.add_data('status', status)
        msg.add_data('reason', reason)
        self.reply(msg.get())
Пример #4
0
 def request_startup(self):
     """ Request the plugin to start over the manager
     """
     print(
         u"Request plugin startup to the manager for '{0}' on '{1}'".format(
             self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.start.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request('manager', msg.get(), timeout=10)
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response from the manager : {0}".format(content))
         if content['status']:
             print(u"Plugin started")
             return True
         else:
             print(u"Error : plugin not started")
             return False
     else:
         raise RuntimeError(
             "MQ Timeout when requesting manager to start the plugin")
Пример #5
0
    def _mdp_reply_plugin_stop(self, data):
        """ Stop the plugin
            @param data : MQ req message

            First, send the MQ Rep to 'ack' the request
            Then, change the plugin status to STATUS_STOP_REQUEST
            Then, quit the plugin by calling force_leave(). This should make the plugin send a STATUS_STOPPED if all is ok

            Notice that no check is done on the MQ req content : we need nothing in it as it is directly addressed to a plugin
        """
        # check if the message is for us
        content = data.get_data()
        if content['name'] != self._name or content[
                'host'] != self.get_sanitized_hostname():
            return

        ### Send the ack over MQ Rep
        msg = MQMessage()
        msg.set_action('plugin.stop.result')
        status = True
        reason = ""
        msg.add_data('status', status)
        msg.add_data('reason', reason)
        self.reply(msg.get())

        ### Change the plugin status
        self._set_status(STATUS_STOP_REQUEST)

        ### Try to stop the plugin
        # if it fails, the manager should try to kill the plugin
        self.force_leave()
Пример #6
0
 def request_stop(self):
     """ Request the plugin to stop
     """
     print(u"Request plugin to stop : '{0}' on '{1}'".format(
         self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.stop.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request("plugin-{0}.{1}".format(self.name, self.host),
                          msg.get(),
                          timeout=30)
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response : {0}".format(content))
         if content['status']:
             print(u"Plugin stopped")
             return True
         else:
             print(u"Error : plugin not stopped")
             return False
     else:
         raise RuntimeError(
             "MQ Timeout when requesting to stop the plugin (the plugin didn't stop itself)"
         )
Пример #7
0
 def WSCommandSend(self, data):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', data['command_id'])
     msg.add_data('cmdparams', data['parameters'])
     return cli.request('xplgw', msg.get(), timeout=10).get()
Пример #8
0
    def test_XplCmd(self, parameters = {}, statParams = None):
        """Send an Xpl cmd with statics parameters by request, if necessary start testcase listener for ack message and 
             check if insert in database is ok.
        """
        if self.get_return_confirmation() :
            schema,  data,  statResult = self.get_XplStat_fromAck(statParams)
            th = threading.Thread(None, self.assert_Xpl_Stat_Ack_Wait, "th_test_0110_xpl-ack_from_{0}".format(self.command_name), (schema,  data, statResult))
            th.start()
            time.sleep(1)
        else : 
            print (u"No ack required for {0}".format(self.command_name))
        if self._device and self.command_id :
            cli = MQSyncReq(zmq.Context())
            msg = MQMessage()
            msg.set_action('cmd.send')
            msg.add_data('cmdid', self.command_id)
            msg.add_data('cmdparams', parameters)
            print (u"Send xpl_cmnd {0}".format(self.command_name))
            cli.request('xplgw', msg.get(), timeout=10)
#            if self.get_return_confirmation() :
#                self.assert_get_last_command_in_db(statResult)
#            else : 
#                print (u"No ack required for {0}".format(self.command_name))
            return True
        else : return False
Пример #9
0
 def _mdp_reply_helper_help(self, data):
     content = data.get_data()
     if 'command' in contens.keys():
         if content['command'] in self.helpers.keys():
             msg = MQMessage()
             msg.set_action('helper.help.result')
             msg.add_data('help', self.helpers[content['command']]['help'])
             self.reply(msg.get())
Пример #10
0
 def _mdp_reply_packages_detail(self):
     """ Reply on the MQ
     """
     msg = MQMessage()
     msg.set_action('package.detail.result')
     for pkg in self._packages:
         msg.add_data(pkg, self._packages[pkg].get_json())
     self.reply(msg.get())
Пример #11
0
 def _mdp_reply_helper_help(self, data):
     content = data.get_data()
     if 'command' in contens.keys():
         if content['command'] in self.helpers.keys():
             msg = MQMessage()
             msg.set_action('helper.help.result')
             msg.add_data('help', self.helpers[content['command']]['help'])
             self.reply(msg.get())
Пример #12
0
 def _mdp_reply_helper_list(self, data):
     """ Return a list of supported helpers
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('helper.list.result')
     msg.add_data('actions', self.helpers.keys())
     self.reply(msg.get())
Пример #13
0
 def _mdp_reply_device_new_get(self, data):
     """ Return a list of new devices detected
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('device.new.result')
     msg.add_data('devices', self.new_devices)
     self.reply(msg.get())
Пример #14
0
 def _mdp_reply_clients_detail(self):
     """ Reply on the MQ
     """
     msg = MQMessage()
     msg.set_action('client.detail.result')
     clients = self._clients.get_detail() 
     for key in clients:
         msg.add_data(key, clients[key])
     self.reply(msg.get())
Пример #15
0
 def _mdp_reply_device_new_get(self, data):
     """ Return a list of new devices detected
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('device.new.result')
     msg.add_data('devices', self.new_devices)
     self.reply(msg.get())
Пример #16
0
 def _mdp_reply_helper_list(self, data):
     """ Return a list of supported helpers
         @param data : MQ req message
     """
     ### Send the ack over MQ Rep
     msg = MQMessage()
     msg.set_action('helper.list.result')
     msg.add_data('actions', self.helpers.keys())
     self.reply(msg.get())
Пример #17
0
 def _mdp_reply(self, plugin, hostname, key, value, element=None):
     msg = MQMessage()
     msg.setaction('config.result')
     msg.add_data('plugin', plugin)
     msg.add_data('hostname', hostname)
     msg.add_data('key', key)
     msg.add_data('value', value)
     if element:
         msg.add_data('element', element)
     print msg.get()
     self.reply(msg.get())
Пример #18
0
 def _mdp_reply(self, plugin, hostname, key, value, element=None):
     msg = MQMessage()
     msg.setaction( 'config.result' )
     msg.add_data('plugin', plugin)
     msg.add_data('hostname', hostname)
     msg.add_data('key', key)
     msg.add_data('value', value)
     if element:
         msg.add_data('element', element)
     print msg.get()
     self.reply(msg.get())
Пример #19
0
def device_params(client_id, dev_type_id):
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('device.params')
    msg.add_data('device_type', dev_type_id)
    res = cli.request('dbmgr', msg.get(), timeout=10)
    result = ""
    if res:
        res = res.get_data()
        result = res['result'];
        result["client_id"] = client_id
    # return the info
    return 200, result
Пример #20
0
 def do_action(self, condition, tests):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', self._params['cmdid'])
     msg.add_data('cmdparams', self._params['cmdparams'])
     # do the request
     res = cli.request('xplgw', msg.get(), timeout=10)
     if res:
         data = res.get_data()
         if not data['status']:
             self._log.error("Command sending to XPL gw failed: {0}".format(res))
     else:
         self._log.error("XPL gw did not respond")
Пример #21
0
 def do_action(self, condition, tests):
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('cmd.send')
     msg.add_data('cmdid', self._params['cmdid'])
     msg.add_data('cmdparams', self._params['cmdparams'])
     # do the request
     res = cli.request('xplgw', msg.get(), timeout=10)
     if res:
         data = res.get_data()
         if not data['status']:
             self._log.error(
                 "Command sending to XPL gw failed: {0}".format(res))
     else:
         self._log.error("XPL gw did not respond")
Пример #22
0
    def loadDevices(cls):
        logger.info("MQ: Loading Devices info")
        Device.clean()
        msg = MQMessage()
        msg.set_action('client.list.get')
        res = cli.request('manager', msg.get(), timeout=10)
        if res is not None:
            _datac = res.get_data()
        else:
            _datac = {}
        session = Session()
        for client in _datac.itervalues(): 
            # for each plugin client, we request the list of devices
            if client["type"] == "plugin":
                msg = MQMessage()
                msg.set_action('device.get')
                msg.add_data('type', 'plugin')
                msg.add_data('name', client["name"])
                msg.add_data('host', client["host"])
                res = cli.request('dbmgr', msg.get(), timeout=10)
                if res is not None:
                    _datad = res.get_data()
                else:
                    _datad = {}
                if 'devices' in _datad:
                    for device in _datad["devices"]:
                        d = Device(id=device["id"], name=device["name"], type=device["device_type_id"], reference=device["reference"])
                        session.add(d)
                        if "commands" in device:
                            for ref, command  in device["commands"].iteritems():
                                c = Command(id=command["id"], name=command["name"], device_id=device["id"], reference=ref, return_confirmation=command["return_confirmation"])
                                session.add(c)
                                c.datatypes = ""
                                for param in command["parameters"]:
                                    p = CommandParam(command_id=c.id, key=param["key"], datatype_id=param["data_type"])
                                    session.add(p)
                                    c.datatypes += param["data_type"]
                                session.add(c)
                        if "sensors" in device:
                            for ref, sensor in device["sensors"].iteritems():
                                s = Sensor(id=sensor["id"], name=sensor["name"], device_id=device["id"], reference=ref, datatype_id=sensor["data_type"], last_value=sensor["last_value"], last_received=sensor["last_received"])
                                session.add(s)

        session.commit()
        session.flush()
Пример #23
0
def device_xplstat_params(did):
    cmd = urlHandler.db.get_xpl_stat(device_id)
    if cmd == None:
        # ERROR
        return
    # get the device
    dev = urlHandler.db.get_device(cmd.device_id)
    if dev == None:
        # ERROR
        return
    # get the device_type
    dt = urlHandler.db.get_device_type_by_id(dev.device_type_id)
    if dt == None:
        # ERROR
        return
    # get the json
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('device_types.get')
    msg.add_data('device_type', dev.device_type_id)
    res = cli.request('manager', msg.get(), timeout=10)
    if res is None:
        return "Bad device type"
    pjson = res.get_data()

    if pjson['json_version'] < 2:
        # ERROR
        return
    # get the json device params for this command
    if pjson['xpl_stats'][cmd.name] is None:
        # ERROR
        return
    for p in pjson['xpl_stats'][cmd.name]['parameters']['device']:
        if request.form.get(p['key']) is None:
            # ERROR
            return
        # go and add the param
        urlHandler.db.add_xpl_stat_param(cmd_id=cmd.id,
                                         key=p['key'],
                                         value=request.form.get(['key']))
    urlHandler.reload_stats()
    return 204, ""
Пример #24
0
def api_ncommand(cid):
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('cmd.send')
    msg.add_data('cmdid', cid)
    # build the commandparams
    cmdparams = {}
    for param in request.args:
        cmdparams[param] = request.args.get(param)
    msg.add_data('cmdparams', cmdparams)
    # do the request
    resp = cli.request('xplgw', msg.get(), timeout=10)
    if resp:
        response = resp.get_data()
        if response['status']:
            return 204, None
        else:
            return 400, {'msg': response['reason']}
    else:
        return 400, {'msg': "XPL gateway does not respond"}
Пример #25
0
def api_ncommand(cid):
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('cmd.send')
    msg.add_data('cmdid', cid)
    # build the commandparams
    cmdparams = {}
    for param in request.args:
        cmdparams[param] = request.args.get(param)
    msg.add_data('cmdparams', cmdparams)
    # do the request
    resp = cli.request('xplgw', msg.get(), timeout=10)
    if resp:
        response = resp.get_data()
        if response['status']:
            return 204, None
        else:
            return 400, {'msg': response['reason']}
    else:
        return 400, {'msg': "XPL gateway does not respond"}
Пример #26
0
def delete_configuration(type, name, host):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.delete')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
	data = result.get_data()
	if 'status' in data:
	    if not data['status']:
                print(result.get())
	        raise RuntimeError("DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
            else:
                return True
        else:
            print(result.get())
	    raise RuntimeError("DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
    else:
        raise RuntimeError("Timeout while deleting configuration for {0}-{1}.{2}".format(type, name, host))
Пример #27
0
def check_config(type, name, host, key, exp_value):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.get')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    msg.add_data('key', key)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
	data = result.get_data()
	if 'status' in data:
	    if not data['status']:
                print(result.get())
	        raise RuntimeError("DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
            else:
                if 'value' in data:
                    if data['value'] != exp_value:
       			print(result.get())
                        raise RuntimeError("The returned value is not the expected value for {0}-{1}.{2} : {3} = {4} but received {5}".format(type, name, host, key, exp_value, data['value']))
		    else:
                        return True
                else:
                    print(result.get())
	            raise RuntimeError("DbMgr did not return a value on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
        else:
	    print(result.get())
	    raise RuntimeError("DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
    else:
        raise RuntimeError("Error while setting configuration for {0}-{1}.{2} : {3} = {4}".format(type, name, host, key, value))
Пример #28
0
    def get_device_list(self, quit_if_no_device=False):
        """ Request the dbmgr component over MQ to get the devices list for this client
            @param quit_if_no_device: if True, exit the plugin if there is no devices
        """
        self.log.info(u"Retrieve the devices list for this client...")
        mq_client = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('device.get')
        msg.add_data('type', 'plugin')
        msg.add_data('name', self._name)
        msg.add_data('host', self.get_sanitized_hostname())
        result = mq_client.request('dbmgr', msg.get(), timeout=10)
        if not result:
            self.log.error(u"Unable to retrieve the device list")
            self.force_leave()
            return []
        else:
            device_list = result.get_data()['devices']
            if device_list == []:
                self.log.warn(u"There is no device created for this client")
                if quit_if_no_device:
                    self.log.warn(
                        u"The developper requested to stop the client if there is no device created"
                    )
                    self.force_leave()
                    return []
            for a_device in device_list:
                self.log.info(u"- id : {0}  /  name : {1}  /  device type id : {2}".format(a_device['id'], \
                                                                                    a_device['name'], \
                                                                                    a_device['device_type_id']))
                # log some informations about the device
                # notice that even if we are not in the XplPlugin class we will display xpl related informations :
                # for some no xpl plugins, there will just be nothing to display.

                # first : the stats
                self.log.info(u"  xpl_stats features :")
                for a_xpl_stat in a_device['xpl_stats']:
                    self.log.info(u"  - {0}".format(a_xpl_stat))
                    self.log.info(u"    Static Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat][
                            'parameters']['static']:
                        self.log.info(u"    - {0} = {1}".format(
                            a_feature['key'], a_feature['value']))
                    self.log.info(u"    Dynamic Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat][
                            'parameters']['dynamic']:
                        self.log.info(u"    - {0}".format(a_feature['key']))

                # then, the commands
                self.log.info(u"  xpl_commands features :")
                for a_xpl_cmd in a_device['xpl_commands']:
                    self.log.info(u" - {0}".format(a_xpl_cmd))
                    self.log.info(u" + Parameters :")
                    for a_feature in a_device['xpl_commands'][a_xpl_cmd][
                            'parameters']:
                        self.log.info(u" - {0} = {1}".format(
                            a_feature['key'], a_feature['value']))

            self.devices = device_list
            return device_list
Пример #29
0
def device_xplstat_params(did):
    cmd = urlHandler.db.get_xpl_stat(device_id)
    if cmd == None:
        # ERROR
        return
    # get the device
    dev = urlHandler.db.get_device(cmd.device_id)
    if dev == None:
        # ERROR
        return
    # get the device_type
    dt = urlHandler.db.get_device_type_by_id(dev.device_type_id)
    if dt == None:
        # ERROR
        return
    # get the json
    cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('device_types.get')
    msg.add_data('device_type', dev.device_type_id)
    res = cli.request('manager', msg.get(), timeout=10)
    if res is None:
        return "Bad device type"
    pjson = res.get_data()
 
    if pjson['json_version'] < 2:
        # ERROR
        return
    # get the json device params for this command
    if pjson['xpl_stats'][cmd.name] is None:
        # ERROR
        return
    for p in pjson['xpl_stats'][cmd.name]['parameters']['device']:
        if request.form.get(p['key']) is None:
            # ERROR
            return
        # go and add the param
        urlHandler.db.add_xpl_stat_param(cmd_id=cmd.id, key=p['key'], value=request.form.get(['key']))
    urlHandler.reload_stats()        
    return 204, ""
Пример #30
0
 def request_startup(self):
     """ Request the plugin to start over the manager
     """
     print(u"Request plugin startup to the manager for '{0}' on '{1}'".format(self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.start.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request('manager', msg.get(), timeout=10) 
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response from the manager : {0}".format(content))
         if content['status']:
             print(u"Plugin started")
             return True
         else:
             print(u"Error : plugin not started")
             return False
     else:
         raise RuntimeError("MQ Timeout when requesting manager to start the plugin")
Пример #31
0
 def request_stop(self):
     """ Request the plugin to stop
     """
     print(u"Request plugin to stop : '{0}' on '{1}'".format(self.name, self.host))
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('plugin.stop.do')
     msg.add_data('name', self.name)
     msg.add_data('host', self.host)
     result = cli.request("plugin-{0}.{1}".format(self.name, self.host), msg.get(), timeout=20) 
     if result:
         msgid, content = result.get()
         content = json.loads(content)
         print(u"Response : {0}".format(content))
         if content['status']:
             print(u"Plugin stopped")
             return True
         else:
             print(u"Error : plugin not stopped")
             return False
     else:
         raise RuntimeError("MQ Timeout when requesting to stop the plugin")
Пример #32
0
    def _mdp_reply_config_set(self, data):
        """ Reply to config.set MQ req
            @param data : MQ req message
        """
        print "#################"
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config set : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config set not available for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config set : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config set : missing 'host' field : {0}".format(data)

        if 'data' not in msg_data:
            status = False
            reason = "Config set : missing 'data' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            data = msg_data['data']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try:
                # we add a configured key set to true to tell the UIs and plugins that there are some configuration elements
                self._db.set_plugin_config(name, host, "configured", True)
                for key in msg_data['data']:
                    self._db.set_plugin_config(name, host, key, data[key])
                self.publish_config_updated(type, name, host)
            except:
                reason = "Error while setting configuration for '{0} {1} on {2}' : {3}".format(
                    type, name, host, traceback.format_exc())
                status = False
                self.log.error(reason)

        msg.add_data('status', status)
        msg.add_data('reason', reason)

        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #33
0
    def query(self, name, key=None):
        """
        Ask the config system for the value. Calling this function will make
        your program wait until it got an answer

        @param name : the plugin of the item requesting the value, must exists in the config database
        @param key : the key to fetch corresponding value
        @return : the value if key != None
                  a dictionnary will all keys/values if key = None
        """
        msg = MQMessage()
        msg.set_action("config.get")
        msg.add_data("type", "plugin")
        msg.add_data("name", name)
        msg.add_data("host", get_sanitized_hostname())
        if key != None:
            msg.add_data("key", key)
        else:
            key = "*"
        self._log.info("Request query config for plugin {0} : key {1}".format(name, key))
        ret = self.cli.request("dbmgr", msg.get(), timeout=QUERY_CONFIG_WAIT)

        ### no response from dbmgr
        if ret is None:
            self._log.error(
                "Query config for plugin {0} on host {1}, key {2} : no response from dbmgr".format(
                    name, get_sanitized_hostname(), key
                )
            )
            return None

        ### response from dbmgr
        else:
            dat = ret.get_data()
            if dat["status"]:
                self._log.debug("Query config : successfull response : {0}".format(ret))
                if key == "*":
                    return dat["data"]
                else:
                    val = dat["value"]
                    # do some cast
                    if val == "None":
                        val = None
                    return val
            else:
                self._log.error("Query config : error returned. Reason : {0}".format(dat["reason"]))
                return None
Пример #34
0
    def _mdp_reply_config_set(self, data):
        """ Reply to config.set MQ req
            @param data : MQ req message
        """
        print "#################"
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config set : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config set not available for type={0}".format(msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config set : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config set : missing 'host' field : {0}".format(data)

        if 'data' not in msg_data:
            status = False
            reason = "Config set : missing 'data' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            data = msg_data['data']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try: 
                # we add a configured key set to true to tell the UIs and plugins that there are some configuration elements
                self._db.set_plugin_config(name, host, "configured", True)
                for key in msg_data['data']:
                    self._db.set_plugin_config(name, host, key, data[key])
                self.publish_config_updated(type, name, host)
            except:
                reason = "Error while setting configuration for '{0} {1} on {2}' : {3}".format(type, name, host, traceback.format_exc())
                status = False
                self.log.error(reason)

        msg.add_data('status', status)
        msg.add_data('reason', reason)

        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #35
0
    def _mdp_reply_devices_result(self, data):
        """ Reply to device.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('device.result')
        status = True

        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Devices request : missing 'type' field : {0}".format(
                data)

        if 'name' not in msg_data:
            status = False
            reason = "Devices request : missing 'name' field : {0}".format(
                data)

        if 'host' not in msg_data:
            status = False
            reason = "Devices request : missing 'host' field : {0}".format(
                data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            #if type == "plugin":
            #    type = DMG_VENDOR_ID
            name = msg_data['name']
            host = msg_data['host']
            dev_list = self._db.list_devices_by_plugin("{0}-{1}.{2}".format(
                type, name, host))
            #dev_json = json.dumps(dev_list, cls=domogik_encoder(), check_circular=False),
            dev_json = dev_list
            print(dev_json)
            msg.add_data('status', status)
            msg.add_data('reason', reason)
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            msg.add_data('devices', dev_json)

        self.reply(msg.get())
Пример #36
0
    def _mdp_reply_devices_create_result(self, data):
        status = True
        reason = False
        result = False
        # get the filled package json
        params = data.get_data()['data']
        # get the json
        cli = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('device_types.get')
        msg.add_data('device_type', params['device_type'])
        res = cli.request('manager', msg.get(), timeout=10)
        del cli
        if res is None:
            status = False
            reason = "Manager is not replying to the mq request" 
        pjson = res.get_data()
        if pjson is None:
            status = False
            reason = "No data for {0} found by manager".format(params['device_type']) 
        pjson = pjson[params['device_type']]
        if pjson is None:
            status = False
            reason = "The json for {0} found by manager is empty".format(params['device_type']) 

        if status:
            # call the add device function
            res = self._db.add_full_device(params, pjson)
            if not res:
                status = False
                reason = "DB failed"
            else:
                status = True
                reason = False
                result = res

        msg = MQMessage()
        msg.set_action('device.create.result')
        if reason:
            msg.add_data('reason', reason)
        if result:
            msg.add_data('result', result)
        msg.add_data('status', status)
        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #37
0
    def get_device_list(self, quit_if_no_device = False):
        """ Request the dbmgr component over MQ to get the devices list for this client
            @param quit_if_no_device: if True, exit the plugin if there is no devices
        """
        self.log.info(u"Retrieve the devices list for this client...")
        mq_client = MQSyncReq(self.zmq)
        msg = MQMessage()
        msg.set_action('device.get')
        msg.add_data('type', 'plugin')
        msg.add_data('name', self._name)
        msg.add_data('host', self.get_sanitized_hostname())
        result = mq_client.request('dbmgr', msg.get(), timeout=10)
        if not result:
            self.log.error(u"Unable to retrieve the device list")
            self.force_leave()
            return []
        else:
            device_list = result.get_data()['devices']
            if device_list == []:
                self.log.warn(u"There is no device created for this client")
                if quit_if_no_device:
                    self.log.warn(u"The developper requested to stop the client if there is no device created")
                    self.force_leave()
                    return []
            for a_device in device_list:
                self.log.info(u"- id : {0}  /  name : {1}  /  device type id : {2}".format(a_device['id'], \
                                                                                    a_device['name'], \
                                                                                    a_device['device_type_id']))
                # log some informations about the device
                # notice that even if we are not in the XplPlugin class we will display xpl related informations :
                # for some no xpl plugins, there will just be nothing to display.

                # first : the stats
                self.log.info(u"  xpl_stats features :")
                for a_xpl_stat in a_device['xpl_stats']:
                    self.log.info(u"  - {0}".format(a_xpl_stat))
                    self.log.info(u"    Static Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat]['parameters']['static']:
                        self.log.info(u"    - {0} = {1}".format(a_feature['key'], a_feature['value']))
                    self.log.info(u"    Dynamic Parameters :")
                    for a_feature in a_device['xpl_stats'][a_xpl_stat]['parameters']['dynamic']:
                        self.log.info(u"    - {0}".format(a_feature['key']))

                # then, the commands
                self.log.info(u"  xpl_commands features :")
                for a_xpl_cmd in a_device['xpl_commands']:
                    self.log.info(u" - {0}".format(a_xpl_cmd))
                    self.log.info(u" + Parameters :")
                    for a_feature in a_device['xpl_commands'][a_xpl_cmd]['parameters']:
                        self.log.info(u" - {0} = {1}".format(a_feature['key'], a_feature['value']))

            self.devices = device_list
            return device_list
Пример #38
0
    def query(self, name, key = None):
        '''
        Ask the config system for the value. Calling this function will make
        your program wait until it got an answer

        @param name : the plugin of the item requesting the value, must exists in the config database
        @param key : the key to fetch corresponding value
        @return : the value if key != None
                  a dictionnary will all keys/values if key = None
        '''
        msg = MQMessage()
        msg.set_action('config.get')
        msg.add_data('type', 'plugin')
        msg.add_data('name', name)
        msg.add_data('host', get_sanitized_hostname())
        if key != None:
            msg.add_data('key', key)
        else:
            key = "*"
        self._log.info("Request query config for plugin {0} : key {1}".format(name, key))
        ret = self.cli.request('dbmgr', msg.get(), timeout=QUERY_CONFIG_WAIT)

        ### no response from dbmgr
        if ret is None:
            self._log.error("Query config for plugin {0} on host {1}, key {2} : no response from dbmgr".format(name, get_sanitized_hostname(), key))
            return None

        ### response from dbmgr
        else:
            dat = ret.get_data()
            if dat['status']:
                self._log.debug("Query config : successfull response : {0}".format(ret))
                if key == "*":
                    return dat['data']
                else:
                    val = dat['value']
                    # do some cast
                    if val == "None":
                        val = None
                    return val
            else:
                self._log.error("Query config : error returned. Reason : {0}".format(dat['reason']))
                return None
Пример #39
0
    def _mdp_reply_devices_result(self, data):
        """ Reply to device.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('device.result')
        status = True

        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Devices request : missing 'type' field : {0}".format(data)

        if 'name' not in msg_data:
            status = False
            reason = "Devices request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Devices request : missing 'host' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            #if type == "plugin":
            #    type = DMG_VENDOR_ID
            name = msg_data['name']
            host = msg_data['host']
            dev_list = self._db.list_devices_by_plugin("{0}-{1}.{2}".format(type, name, host))
            #dev_json = json.dumps(dev_list, cls=domogik_encoder(), check_circular=False),
            dev_json = dev_list
            print(dev_json)
            msg.add_data('status', status)
            msg.add_data('reason', reason)
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            msg.add_data('devices', dev_json)

        self.reply(msg.get())
Пример #40
0
    def _mdp_reply_config_delete(self, data):
        """ Reply to config.delete MQ req
            Delete all the config items for the given type, name and host
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config request not available for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try:
                self._db.del_plugin_config(name, host)
                self.log.info(u"Delete config for {0} {1}".format(type, name))
                self.publish_config_updated(type, name, host)
            except:
                status = False
                reason = "Error while deleting configuration for '{0} {1} on {2} : {3}".format(
                    type, name, host, traceback.format_exc())
                self.log.error(reason)

        msg.add_data('reason', reason)
        msg.add_data('status', status)

        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #41
0
    def _mdp_reply_config_delete(self, data):
        """ Reply to config.delete MQ req
            Delete all the config items for the given type, name and host
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config request not available for type={0}".format(msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            try:
                self._db.del_plugin_config(name, host)
                self.log.info(u"Delete config for {0} {1}".format(type, name))
                self.publish_config_updated(type, name, host)
            except:
                status = False
                reason = "Error while deleting configuration for '{0} {1} on {2} : {3}".format(type, name, host, traceback.format_exc())
                self.log.error(reason)

        msg.add_data('reason', reason)
        msg.add_data('status', status)

        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #42
0
 def _mdp_reply_device_types(self, data):
     """ Reply on the MQ
         @param data : message data
     """
     msg = MQMessage()
     msg.set_action('device_types.result')
     if 'device_type' not in data.get_data():
         for dev in self._device_types:
             msg.add_data(dev, self._device_types[dev])
     else:
         device_type = data.get_data()['device_type']
         if self._device_types.has_key(device_type):
             msg.add_data(device_type, self._device_types[device_type])
         else:
             msg.add_data(device_type, None)
     self.reply(msg.get())
Пример #43
0
 def refreshClientDevice(self,  client):
     """Request a refresh domogik device data for a IRTrans Client."""
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('device.get')
     msg.add_data('type', 'plugin')
     msg.add_data('name', self._xplPlugin.get_plugin_name())
     msg.add_data('host', get_sanitized_hostname())
     devices = cli.request('dbmgr', msg.get(), timeout=10).get()
     for a_device in devices:
         if a_device['device_type_id'] == client._device['device_type_id']  and a_device['id'] == client._device['id'] :
             if a_device['name'] != client.device['name'] : # rename and change key client id
                 old_id = getIRTransId(client._device)
                 self.irTransClients[getIRTransId(a_device)] = self.irTransClients.pop(old_id)
                 self._xplPlugin.log.info(u"IRTransciever Client {0} is rename {1}".format(old_id,  getIRTransId(a_device)))
             client.updateDevice(a_device)
             break
Пример #44
0
def check_config(type, name, host, key, exp_value):
    cli = MQSyncReq(zmq.Context())
    msg = MQMessage()
    msg.set_action('config.get')
    msg.add_data('type', type)
    msg.add_data('host', host)
    msg.add_data('name', name)
    msg.add_data('key', key)
    result = cli.request('dbmgr', msg.get(), timeout=10)
    if result:
        data = result.get_data()
        if 'status' in data:
            if not data['status']:
                print(result.get())
                raise RuntimeError(
                    "DbMgr did not return status true on a config.set for {0}-{1}.{2} : {3} = {4}"
                    .format(type, name, host, key, value))
            else:
                if 'value' in data:
                    if data['value'] != exp_value:
                        print(result.get())
                        raise RuntimeError(
                            "The returned value is not the expected value for {0}-{1}.{2} : {3} = {4} but received {5}"
                            .format(type, name, host, key, exp_value,
                                    data['value']))
                    else:
                        return True
                else:
                    print(result.get())
                    raise RuntimeError(
                        "DbMgr did not return a value on a config.set for {0}-{1}.{2} : {3} = {4}"
                        .format(type, name, host, key, value))
        else:
            print(result.get())
            raise RuntimeError(
                "DbMgr did not return a status on a config.set for {0}-{1}.{2} : {3} = {4}"
                .format(type, name, host, key, value))
    else:
        raise RuntimeError(
            "Error while setting configuration for {0}-{1}.{2} : {3} = {4}".
            format(type, name, host, key, value))
Пример #45
0
 def _mdp_reply_helper_do(self, msg):
     contens = msg.get_data()
     if 'command' in contens.keys():
         if contens['command'] in self.helpers.keys():
             if 'parameters' not in contens.keys():
                 contens['parameters'] = {}
                 params = []
             else:
                 params = []
                 for key, value in contens['parameters'].items():
                     params.append( "{0}='{1}'".format(key, value) )
             command = "self.{0}(".format(self.helpers[contens['command']]['call'])
             command += ", ".join(params)
             command += ")"
             result = eval(command)
             # run the command with all params
             msg = MQMessage()
             msg.set_action('helper.do.result')
             msg.add_data('command', contens['command'])
             msg.add_data('parameters', contens['parameters'])
             msg.add_data('result', result)
             self.reply(msg.get())
Пример #46
0
 def _mdp_reply_helper_do(self, msg):
     contens = msg.get_data()
     if 'command' in contens.keys():
         if contens['command'] in self.helpers.keys():
             if 'parameters' not in contens.keys():
                 contens['parameters'] = {}
                 params = []
             else:
                 params = []
                 for key, value in contens['parameters'].items():
                     params.append( "{0}='{1}'".format(key, value) )
             command = "self.{0}(".format(self.helpers[contens['command']]['call'])
             command += ", ".join(params)
             command += ")"
             result = eval(command)
             # run the command with all params
             msg = MQMessage()
             msg.set_action('helper.do.result')
             msg.add_data('command', contens['command'])
             msg.add_data('parameters', contens['parameters'])
             msg.add_data('result', result)
             self.reply(msg.get())
Пример #47
0
 def refreshClientDevice(self, client):
     """Request a refresh domogik device data for a IRTrans Client."""
     cli = MQSyncReq(zmq.Context())
     msg = MQMessage()
     msg.set_action('device.get')
     msg.add_data('type', 'plugin')
     msg.add_data('name', self._xplPlugin.get_plugin_name())
     msg.add_data('host', get_sanitized_hostname())
     devices = cli.request('dbmgr', msg.get(), timeout=10).get()
     for a_device in devices:
         if a_device['device_type_id'] == client._device[
                 'device_type_id'] and a_device['id'] == client._device[
                     'id']:
             if a_device['name'] != client.device[
                     'name']:  # rename and change key client id
                 old_id = getIRTransId(client._device)
                 self.irTransClients[getIRTransId(
                     a_device)] = self.irTransClients.pop(old_id)
                 self._xplPlugin.log.info(
                     u"IRTransciever Client {0} is rename {1}".format(
                         old_id, getIRTransId(a_device)))
             client.updateDevice(a_device)
             break
Пример #48
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device.get')
msg.add_data('type', 'plugin')
msg.add_data('name', 'diskfree')
msg.add_data('host', 'darkstar')
print cli.request('dbmgr', msg.get(), timeout=10).get()

Пример #49
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('device_types.get')
msg.add_data('device_type', 'diskfree.disk_usage')
print cli.request('manager', msg.get(), timeout=10).get()


Пример #50
0
    def _mdp_reply_config_get(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config request not available for type={0}".format(
                msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if 'key' not in msg_data:
            get_all_keys = True
            key = "*"
        else:
            get_all_keys = False
            key = msg_data['key']

        if status == False:
            self.log.error(reason)
        else:
            reason = ""
            type = msg_data['type']
            name = msg_data['name']
            host = msg_data['host']
            msg.add_data('type', type)
            msg.add_data('name', name)
            msg.add_data('host', host)
            msg.add_data(
                'key', key
            )  # we let this here to display key or * depending on the case
            try:
                if get_all_keys == True:
                    config = self._db.list_plugin_config(name, host)
                    self.log.info(
                        u"Get config for {0} {1} with key '{2}' : value = {3}".
                        format(type, name, key, config))
                    json_config = {}
                    for elt in config:
                        json_config[elt.key] = self.convert(elt.value)
                    msg.add_data('data', json_config)
                else:
                    value = self._fetch_techno_config(name, host, key)
                    # temporary fix : should be done in a better way (on db side)
                    value = self.convert(value)
                    self.log.info(
                        u"Get config for {0} {1} with key '{2}' : value = {3}".
                        format(type, name, key, value))
                    msg.add_data('value', value)
            except:
                status = False
                reason = "Error while getting configuration for '{0} {1} on {2}, key {3}' : {4}".format(
                    type, name, host, key, traceback.format_exc())
                self.log.error(reason)

        msg.add_data('reason', reason)
        msg.add_data('status', status)

        self.log.debug(msg.get())
        self.reply(msg.get())
Пример #51
0
    def _send_xpl_command(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
                Needed info in data:
                - cmdid         => command id to send
                - cmdparams     => key/value pair of all params needed for this command
        """
        with self._db.session_scope():
            self.log.info(u"Received new cmd request: {0}".format(data))
            failed = False

            request = data.get_data()
            if 'cmdid' not in request:
                failed = "cmdid not in message data"
            if 'cmdparams' not in request:
                failed = "cmdparams not in message data"
            if not failed:
                # get the command
                cmd = self._db.get_command(request['cmdid'])
                if cmd is not None:
                    if cmd.xpl_command is not None:
                        xplcmd = cmd.xpl_command
                        xplstat = self._db.get_xpl_stat(xplcmd.stat_id)
                        if xplstat is not None:
                            # get the device from the db
                            dev = self._db.get_device(int(cmd.device_id))
                            msg = XplMessage()
                            # update the client list
                            if not dev[
                                    'client_id'] in self.client_xpl_map.keys():
                                self._load_client_to_xpl_target()
                            if not dev[
                                    'client_id'] in self.client_xpl_map.keys():
                                failed = "Can not fincd xpl source for {0} client_id".format(
                                    dev['client_id'])
                            else:
                                msg.set_target(
                                    self.client_xpl_map[dev['client_id']])
                            msg.set_source(self.myxpl.get_source())
                            msg.set_type("xpl-cmnd")
                            msg.set_schema(xplcmd.schema)
                            # static params
                            for p in xplcmd.params:
                                msg.add_data({p.key: p.value})
                            # dynamic params
                            for p in cmd.params:
                                if p.key in request['cmdparams']:
                                    value = request['cmdparams'][p.key]
                                    # chieck if we need a conversion
                                    if p.conversion is not None and p.conversion != '':
                                        if dev['client_id'] in self.client_conversion_map:
                                            if p.conversion in self.client_conversion_map[
                                                    dev['client_id']]:
                                                exec(
                                                    self.client_conversion_map[
                                                        dev['client_id']][
                                                            p.conversion])
                                                value = locals()[p.conversion](
                                                    value)
                                    msg.add_data({p.key: value})
                                else:
                                    failed = "Parameter ({0}) for device command msg is not provided in the mq message".format(
                                        p.key)
                            if not failed:
                                # send out the msg
                                self.log.debug(
                                    u"sending xplmessage: {0}".format(msg))
                                self.myxpl.send(msg)
                                ### Wait for answer
                                stat_received = 0
                                if xplstat != None:
                                    # get xpl message from queue
                                    self.log.debug(
                                        u"Command : wait for answer...")
                                    sub = MQSyncSub(self.zmq, 'rest-command',
                                                    ['device-stats'])
                                    stat = sub.wait_for_event()
                                    if stat is not None:
                                        reply = json.loads(stat['content'])
                                        reply_msg = MQMessage()
                                        reply_msg.set_action('cmd.send.result')
                                        reply_msg.add_data('stat', reply)
                                        reply_msg.add_data('status', True)
                                        reply_msg.add_data('reason', None)
                                        self.log.debug(u"mq reply".format(
                                            reply_msg.get()))
                                        self.reply(reply_msg.get())
                        else:
                            failed = "xplStat {0} does not exists".format(
                                xplcmd.stat_id)
                    else:
                        failed = "Command {0} has no associated xplcommand".format(
                            cmd.id)
                else:
                    failed = "Command {0} does not exists".format(
                        request['cmdid'])

            if failed:
                self.log.error(failed)
                reply_msg = MQMessage()
                reply_msg.set_action('cmd.send.result')
                reply_msg.add_data('status', False)
                reply_msg.add_data('reason', failed)
                self.log.debug(u"mq reply".format(reply_msg.get()))
                self.reply(reply_msg.get())
Пример #52
0
def client_config(client_id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.detail.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        config = detaila[client_id]['data']['configuration']
    else:
        config = {}
    known_items = []

    # dynamically generate the wtfform
    class F(Form):
        submit = SubmitField("Send")
        pass
    for item in config:
        # keep track of the known fields
        known_items.append(item["key"])
        # handle required
        if item["required"] == "yes":
            arguments = [Required()]
        else:
            arguments = []
        # fill in the field
        if 'value' in item:
            default = item["value"]
        else:
            default = item["default"]
        # build the field
        if item["type"] == "boolean":
            field = BooleanField(item["name"], arguments, description=item["description"], default=default)
        elif item["type"] == "number":
            field = IntegerField(item["name"], arguments, description=item["description"], default=default)
        elif item["type"] == "enum":
            choices = []
            for choice in item["choices"]:
                choices.append((choice, choice))
            field = SelectField(item["name"], arguments, description=item["description"], choices=choices, default=default)
        else:
            field = TextField(item["name"], arguments, description=item["description"], default=default)
        # add the field
        setattr(F, item["key"], field)
    # add the submit button
    field = submit = SubmitField("Send")
    setattr(F, "submit", field)

    form = F()

    if request.method == 'POST' and form.validate():
        # build the requested config set
        data = {}
        for arg, value in list(request.form.items()):
            if arg in known_items:
                data[arg] = value
        # build the message
        msg = MQMessage()
        msg.set_action('config.set')
        tmp = client_id.split('-')
        msg.add_data('type', tmp[0])
        tmp = tmp[1].split('.')
        msg.add_data('host', tmp[1])
        msg.add_data('name', tmp[0])
        msg.add_data('data', data)
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                flash(gettext("Config saved successfull"), 'success')
            else:
                flash(gettext("Config saved failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(gettext("DbMgr did not respond on the config.set, check the logs"), 'danger')

    return render_template('client_config.html',
            form = form,
            clientid = client_id,
            mactve="clients",
            active = 'config'
            )
Пример #53
0
def get_device_params(dev_type_id, zmq=None):
    if zmq:
        cli = MQSyncReq(zmq)
    else:
        cli = MQSyncReq(urlHandler.zmq_context)
    msg = MQMessage()
    msg.set_action('device_types.get')
    msg.add_data('device_type', dev_type_id)
    res = cli.request('manager', msg.get(), timeout=10)
    if res is None:
        raise Exception("Bad device type (MQ)")
    pjson = res.get_data()
    if pjson is None:
        raise Exception("Bad device type (json)")
    pjson = pjson[dev_type_id]
    if pjson is None:
        raise Exception("Device type not found")
    # parse the data
    ret = {}
    ret['commands'] = []
    ret['global'] = []
    if 'parameters' in pjson['device_types'][dev_type_id]:
        ret['global'] = pjson['device_types'][dev_type_id]['parameters']
    ret['xpl_stat'] = []
    ret['xpl_cmd'] = []
    # find all features for this device
    for c in pjson['device_types'][dev_type_id]['commands']:
        if not c in pjson['commands']:
            break
        cm = pjson['commands'][c]
        ret['commands'].append(c)
        # we must have an xpl command
        if not 'xpl_command' in cm:
            break
        # we have an xpl_command => find it
        if not cm['xpl_command'] in pjson['xpl_commands']:
            raise "Command references an unexisting xpl_command"
        # find the xpl commands that are neede for this feature
        cmd = pjson['xpl_commands'][cm['xpl_command']].copy()
        cmd['id'] = c
        # finc the xpl_stat message
        cmd = pjson['xpl_commands'][cm['xpl_command']].copy()
        cmd['id'] = c
        # finc the xpl_stat message
        if not 'xplstat_name' in cmd:
            break
        if not cmd['xplstat_name'] in pjson['xpl_stats']:
            raise Exception("XPL command references an unexisting xpl_stat")
        stat = pjson['xpl_stats'][cmd['xplstat_name']].copy()
        stat['id'] = cmd['xplstat_name']
        # remove all parameters
        cmd['parameters'] = cmd['parameters']['device']
        del cmd['parameters']
        ret['xpl_cmd'].append(cmd)
        if stat is not None:
            # remove all parameters
            stat['parameters'] = stat['parameters']['device']
            del stat['parameters']
            ret['xpl_stat'].append(stat)
        del stat
        del cmd
    ret['global'] = [
        x for i, x in enumerate(ret['global'])
        if x not in ret['global'][i + 1:]
    ]
    return ret
Пример #54
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('config.get')
msg.add_data('type', 'plugin')
msg.add_data('host', 'darkstar')
msg.add_data('name', 'diskfree')
print cli.request('dbmgr', msg.get(), timeout=10).get()

Пример #55
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('helper.help.get')
msg.add_data('command', 'scan')
print cli.request('velbus', msg.get(), timeout=10).get()

Пример #56
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('cmd.send')
msg.add_data('cmdid', 1)
msg.add_data('cmdparams', {'level': 0})
print cli.request('xplgw', msg.get(), timeout=10).get()


Пример #57
0
def client_config(client_id):
    cli = MQSyncReq(app.zmq_context)
    msg = MQMessage()
    msg.set_action('client.detail.get')
    res = cli.request('manager', msg.get(), timeout=10)
    if res is not None:
        detaila = res.get_data()
        config = detaila[client_id]['data']['configuration']
    else:
        config = {}
    known_items = []

    # dynamically generate the wtfform
    class F(Form):
        submit = SubmitField("Send")
        pass

    for item in config:
        # keep track of the known fields
        known_items.append(item["key"])
        # handle required
        if item["required"] == "yes":
            arguments = [Required()]
        else:
            arguments = []
        # fill in the field
        if 'value' in item:
            default = item["value"]
        else:
            default = item["default"]
        # build the field
        if item["type"] == "boolean":
            field = BooleanField(item["name"],
                                 arguments,
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "number":
            field = IntegerField(item["name"],
                                 arguments,
                                 description=item["description"],
                                 default=default)
        elif item["type"] == "enum":
            choices = []
            for choice in item["choices"]:
                choices.append((choice, choice))
            field = SelectField(item["name"],
                                arguments,
                                description=item["description"],
                                choices=choices,
                                default=default)
        else:
            field = TextField(item["name"],
                              arguments,
                              description=item["description"],
                              default=default)
        # add the field
        setattr(F, item["key"], field)
    # add the submit button
    field = submit = SubmitField("Send")
    setattr(F, "submit", field)

    form = F()

    if request.method == 'POST' and form.validate():
        # build the requested config set
        data = {}
        for arg, value in list(request.form.items()):
            if arg in known_items:
                data[arg] = value
        # build the message
        msg = MQMessage()
        msg.set_action('config.set')
        tmp = client_id.split('-')
        msg.add_data('type', tmp[0])
        tmp = tmp[1].split('.')
        msg.add_data('host', tmp[1])
        msg.add_data('name', tmp[0])
        msg.add_data('data', data)
        res = cli.request('dbmgr', msg.get(), timeout=10)
        if res is not None:
            data = res.get_data()
            if data["status"]:
                flash(gettext("Config saved successfull"), 'success')
            else:
                flash(gettext("Config saved failed"), 'warning')
                flash(data["reason"], 'danger')
        else:
            flash(
                gettext(
                    "DbMgr did not respond on the config.set, check the logs"),
                'danger')

    return render_template('client_config.html',
                           form=form,
                           clientid=client_id,
                           mactve="clients",
                           active='config')
Пример #58
0
#!/usr/bin/python

import zmq
from zmq.eventloop.ioloop import IOLoop
from domogik.mq.reqrep.client import MQSyncReq
from domogik.mq.message import MQMessage

cli = MQSyncReq(zmq.Context())
msg = MQMessage()
msg.set_action('plugin.start.do')
msg.add_data('name', 'diskfree')
msg.add_data('host', 'darkstar')
print cli.request('manager', msg.get(), timeout=10).get()