Ejemplo n.º 1
0
def get_sql_msg(src_ip,state):
    text = '${device/db_ip} ${device/db_port} ${device/db_user} ${device/db_passwd}'
    rpc_handle = HttpHandler()
    rpc_handle.login()
    result = rpc_handle.getResponseData("device_router","DeviceRouter","compile_text",[{"dev_ip":src_ip,"text":text}])
    if result:
        dbcfg = result.split()
        conn = None
        import MySQLdb
        try:
            conn = MySQLdb.connect(host=dbcfg[0], user=dbcfg[2],port=int(dbcfg[1]), passwd=dbcfg[3],db="ssoc",init_command="SET NAMES utf8")
            conn.autocommit(1)
            curs = conn.cursor()
            sql1 = "select b.mem_address,b.mem_port,a.control_address,a.control_port from cloud_virtual_server a " \
                   "LEFT JOIN cloud_virtual_member b on a.v_id = b.pool_id where b.mem_address='%s'"%src_ip
            curs.execute(sql1)
            conn.commit()
            result = curs.fetchall()
            #修改每个主机对应的端口状态
            for i in result:
                mem_address,mem_port,control_host,control_port = i
                set_member(mem_address,mem_port,str(state),control_host,control_port)
        except:
            logger.warning("连接数据库失败")
    else:
        logger.warning("获取数据库连接参数失败!%s可能不存在"%src_ip)
Ejemplo n.º 2
0
 def __init__(self, parent, door_controller_url, keepalive_period_secs):
     Thread.__init__(self)
     self.the_parent = parent
     self.door_controller_url = door_controller_url
     self.keepalive_period_secs = keepalive_period_secs
     self.continue_running = True
     self.httpHandler = HttpHandler("requests")
Ejemplo n.º 3
0
class CalendarUpdateThread(Thread):

    def __init__(self, parent, cal_feeds, cal_update_period_secs):
        Thread.__init__(self)
        self.the_parent = parent
        self.cal_feeds = cal_feeds
        self.cal_update_period_secs = cal_update_period_secs
        self.continue_running = True
        self.httpHandler = HttpHandler("requests")

    def stop(self):
        self.continue_running = False

    def run(self):
        while self.continue_running:
            calendars = []
            for calFeed in self.cal_feeds:
                ics_str = self.httpHandler.getTextResponse(calFeed["icsUrl"])
                if len(ics_str) <= 0:
                    continue

                print ("Cal len = ", len(ics_str))
                cal_parser = ICalParser.ICalParser()
                cal_parser.from_string(ics_str)
                dt_now = datetime.now()
                dt_end = dt_now + timedelta(days=7)
                dates = cal_parser.get_event_instances(dt_now.strftime("%Y%m%d"),dt_end.strftime("%Y%m%d"))
                calendars.append(dates)
                self.the_parent.setNewCalendarEntries(calendars)
            time.sleep(self.cal_update_period_secs)
Ejemplo n.º 4
0
 def __init__(self, parent, cal_feeds, cal_update_period_secs):
     Thread.__init__(self)
     self.the_parent = parent
     self.cal_feeds = cal_feeds
     self.cal_update_period_secs = cal_update_period_secs
     self.continue_running = True
     self.httpHandler = HttpHandler("requests")
Ejemplo n.º 5
0
 def sendResult(self, exam_id, is_teacher_signed, students_list):
     http_handler = HttpHandler.getInstance()
     http_handler.postAttendanceResult(
         data={
             "exam_id": int(exam_id),
             "is_teacher_signed": is_teacher_signed,
             "present_students_list": students_list
         })
Ejemplo n.º 6
0
 def __init__(self, automation_server_info, update_secs):
     self.list_update_thread = None
     self.data_lock = Lock()
     self.data_updated = False
     self.cur_actions = {}
     self.automation_server_info = automation_server_info
     self.update_secs = update_secs
     self.httpHandler = HttpHandler("requests")
Ejemplo n.º 7
0
 def __init__(self, parent, automation_server_info, update_period_secs, data_ready_callback):
     Thread.__init__(self)
     self.the_parent = parent
     self.automation_server_info = automation_server_info
     self.update_period_secs = update_period_secs
     self.data_ready_callback = data_ready_callback
     self.rooms = {}
     self.actions = []
     self.httpHandler = HttpHandler("requests")
     # Add in actions for statically defined automation servers now
     for server_info in self.automation_server_info:
         if server_info["reqStr"] == "":
             self.data_ready_callback(server_info["cmdList"], server_info["serverType"])
Ejemplo n.º 8
0
class AutomationServer:

    def __init__(self, automation_server_info, update_secs):
        self.list_update_thread = None
        self.data_lock = Lock()
        self.data_updated = False
        self.cur_actions = {}
        self.automation_server_info = automation_server_info
        self.update_secs = update_secs
        self.httpHandler = HttpHandler("requests")

    def start(self):
        self.list_update_thread = AutomationServerUpdateThread(self, self.automation_server_info, self.update_secs, self.setNewActionEntries)
        self.list_update_thread.start()

    def stop(self):
        if self.list_update_thread is not None:
            self.list_update_thread.stop()

    def setNewActionEntries(self, actions, serverType):
        with self.data_lock:
            self.cur_actions[serverType] = actions
            self.data_updated = True
            print (str(len(actions)) + " new actions from server type " + serverType)

    def getActionsDataJson(self):
        print ("Tablet requesting actions")
        cal_str = json.dumps(self.cur_actions)
        return cal_str

    def execCommand(self, cmdParam):
        reg = r'_(.*?)_'
        grp = re.match(reg, cmdParam)
        if grp is None or grp.lastindex is None:
            return "FAIL"
        remain = cmdParam[len(grp.group(0)):]
        for serv_info in self.automation_server_info:
            if serv_info["serverType"] == grp.group(1):
                 cmdUrl = serv_info["baseUrl"] + serv_info["cmdPrefix"] + remain + serv_info["cmdSuffix"]
                 self.sendHttpCommand(cmdUrl)
                 break
        return "OK"

    def sendHttpCommand(self, cmdUrl):
        resp_str = self.httpHandler.getTextResponse(cmdUrl)
        return "OK"
Ejemplo n.º 9
0
class DoorControllerKeepAliveThread(Thread):
    def __init__(self, parent, door_controller_url, keepalive_period_secs):
        Thread.__init__(self)
        self.the_parent = parent
        self.door_controller_url = door_controller_url
        self.keepalive_period_secs = keepalive_period_secs
        self.continue_running = True
        self.httpHandler = HttpHandler("requests")

    def stop(self):
        self.continue_running = False

    def run(self):
        while self.continue_running:
            statusStr = self.httpHandler.getTextResponse(self.door_controller_url)
            if len(statusStr) > 0:
                print("Front Door Watchdog reset")
            else:
                print("FAILED TO RESET Front Door Watchdog")
            time.sleep(self.keepalive_period_secs)
Ejemplo n.º 10
0
 def __init__(self,dev_ip):
     self.conn = None
     self.dev_ip = dev_ip
     self.rpc_handle = HttpHandler()
     self.rpc_handle.login()
     self.getDabaseConnect()
Ejemplo n.º 11
0
class SwitchCTMS:
    def __init__(self,dev_ip):
        self.conn = None
        self.dev_ip = dev_ip
        self.rpc_handle = HttpHandler()
        self.rpc_handle.login()
        self.getDabaseConnect()

    def complieText(self,dev_ip,text):
        return self.rpc_handle.getResponseData("device_router","DeviceRouter","compile_text",[{"dev_ip":dev_ip,"text":text}])

    def getDeviceInfo(self,devclass = "/zport/dmd/Devices/",devIp=None):
        param = [{"start":0,
        	"limit":50,
            "dir":"ASC",
            "sort":"name",
            "params":"{\"productionState\":[\"1000\"]",
            "uid":devclass}]
        if devIp:
            param[0]["params"]= param[0]["params"] + ',"ipAddress":"'+devIp+'"}'
        else:
            param[0]["params"]= param[0]["params"]+"}"
        return self.rpc_handle.getResponseData("device_router","DeviceRouter","getDevices",param)

    def getDabaseConnect(self):
        text = '${device/db_ip} ${device/db_port} ${device/db_user} ${device/db_passwd}'
        result = self.complieText(self.dev_ip,text)
        if result:
            dbcfg = result.split()
            conn = None
            import MySQLdb
            try:
                self.conn = MySQLdb.connect(host=dbcfg[0], user=dbcfg[2],port=int(dbcfg[1]), passwd=dbcfg[3],db="ssoc",reconnect=1,init_command="SET NAMES utf8")
                self.conn.autocommit(1)
            except:
                logger.warning("连接数据库失败")
        else:
            logger.warning("获取数据库连接参数失败!%s可能不存在"%self.dev_ip)

    def DelBackDeviceInfo(self):
        logger.debug("being DelBackDeviceInfo")
        sql = 'select back_ip,back_id from cloud_master_back_info where master_ip = "%s"'%self.dev_ip
        self.conn.query(sql)
        result = self.conn.use_result()
        rows =  result.fetch_row(0,1)
        sql = 'delete from cloud_master_back_info where master_ip = "%s"'%self.dev_ip
        curs = self.conn.cursor()
        curs.execute(sql)
        logger.debug("end DelBackDeviceInfo")
        return rows

    def StopService(self,dev_ip):
        param = "${device/zCommandPassword} ${device/zCommandPort} ${device/zCommandUsername} ${device/zSybaseModelerOSUser}"
        param = self.complieText(dev_ip,param)
        if param:
            params_list = param.split()
            cmd = 'sudo sshpass -p %s ssh -p %s %s@%s su - %s -c "echo null_acb |stopctms;killall -9 ctms;echo ok"""'%(params_list[0],params_list[1],params_list[2],dev_ip,params_list[3])
            logger.info("exec command :%s"%cmd)
            cmd = "ls"
            p = subprocess.Popen(cmd,bufsize=1,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            logger.info("---StopCTMSService result----\n%s"%p.stdout.read())
        else:
            logger.warning("停止CTMS服务失败,编译停止命令出错")

    def StartService(self,dev_ip):
        param = "${device/zCommandPassword} ${device/zCommandPort} ${device/zCommandUsername} ${device/zSybaseModelerOSUser}"
        param = self.complieText(dev_ip,param)
        if param:
            params_list = param.split()
            cmd = 'sudo sshpass -p %s ssh -p %s %s@%s su - %s -c "echo null_acb |stopctms;killall -9 ctms;startctms;echo ok"""'%(params_list[0],params_list[1],params_list[2],dev_ip,params_list[3])
            logger.info("exec command :%s"%cmd)
            cmd = "pwd"
            p = subprocess.Popen(cmd,bufsize=1,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            logger.info("---StartService result----\n%s"%p.stdout.read())
        else:
            logger.warning("启动CTMS服务失败,编译停止命令出错")

    def ChangeDeviceClass(self,devid,newClass):
        #param = [{"uids":["/zport/dmd/Devices/Server/Webserver/Apache/devices/192.168.1.166"],"target":"/zport/dmd/Devices/Client"}]
        param = [{"uids":[devid],"target":newClass}]
        logger.info("修改设备%s的类型%s"%(devid,newClass))
        result = self.rpc_handle.getResponseData("acg_router","ACGRouter","changeDevCls",param)
        logger.info("修改设备%s的类型%s:返回%s"%(devid,newClass,result))


    def DoStartBack(self):
        #   2。是否已经启动备机(已经启动备机,则忽略)
        sql = 'select back_ip,back_id from cloud_master_back_info where master_ip = "%s"'%self.dev_ip
        self.conn.query(sql)
        result = self.conn.use_result()
        rows =  result.fetch_row(0,1)
        if len(rows) > 0:
            logger.warning("设备[%s]的备机已经启动,忽略启动备机操作"%self.dev_ip)
        else:
            #查询可用的备机
            sql = """select  virsh_id,virsh_ip from cloud_virsh a,
            (select domain_id from cloud_virsh where virsh_ip = "%s")c
            where a.domain_id = c.domain_id
            and a.device_type = 0
            and a.virsh_id not in(select back_id from cloud_master_back_info)"""%self.dev_ip
            self.conn.query(sql)
            result = self.conn.use_result()
            rows =  result.fetch_row(0,1)
            if len(rows)<= 0:
                logger.warning("设备[%s]的备机启动失败,没有空闲的备机"%self.dev_ip)
            else:
                result =self.getDeviceInfo(devIp=rows[0]["virsh_ip"])
                if result["totalCount"]>0:
                    logger.info("设备[%s]的备机[%s]开始启动"%(self.dev_ip,rows[0]["virsh_ip"]))
                    #启动CTMS
                    self.StartService(rows[0]["virsh_ip"])
                    #修改设备分类
                    back_devid = result["devices"][0]["uid"]
                    paths = back_devid.split("/")[0:-2]
                    paths.append(APP_CLASS)
                    newClass = "/".join(paths)
                    self.ChangeDeviceClass(back_devid,newClass)
                    #登记主备
                    curs = self.conn.cursor()
                    sql = "insert into cloud_master_back_info(back_id,back_ip,master_ip) values('%s','%s','%s')"%(back_devid,rows[0]["virsh_ip"],self.dev_ip)
                    curs.execute(sql)
                    #重启zendmd
                    os.system("zencommand restart")
                    logger.warning("设备[%s]的切换备机完成"%self.dev_ip)
                else:
                    logger.warning("设备[%s]的备机不存在"%self.dev_ip)


    def DoStopBack(self):
        import pydevd
        pydevd.settrace('127.0.0.1', port=7777, stdoutToServer=True, stderrToServer=True)
        backlist =self.DelBackDeviceInfo()
        if len(backlist) ==0:
            logger.warning("设备%s没有找到备机"%self.dev_ip)
        else:
            for back in backlist:
                #获取备份机的设备信息
                result = self.getDeviceInfo(devIp=back["back_ip"])
                #如果备机还存在
                if result["totalCount"]>0:
                    #移动到上一级设备类
                    paths= result["devices"][0]["uid"].split("/")
                    if paths[-3] == APP_CLASS:
                        paths = paths[0:-3]
                        self.ChangeDeviceClass(result["devices"][0]["uid"],"/".join(paths))
                    self.StopService(back["back_ip"])
                    os.system("zencommand restart")
                    logger.warning("设备[%s]的停止备机完成"%self.dev_ip)
                else:
                    logger.warning("设备[%s]的备机[%s]已不存在"%(self.dev_ip,back["back_ip"]))
Ejemplo n.º 12
0
 def getAttendanceList(self):
    httpHandler = HttpHandler.getInstance()
    self.attendanceList = httpHandler.getAttendanceList()
Ejemplo n.º 13
0
class AutomationServerUpdateThread(Thread):
    the_parent = None
    continue_running = True
    automation_server_urls = []

    def __init__(self, parent, automation_server_info, update_period_secs, data_ready_callback):
        Thread.__init__(self)
        self.the_parent = parent
        self.automation_server_info = automation_server_info
        self.update_period_secs = update_period_secs
        self.data_ready_callback = data_ready_callback
        self.rooms = {}
        self.actions = []
        self.httpHandler = HttpHandler("requests")
        # Add in actions for statically defined automation servers now
        for server_info in self.automation_server_info:
            if server_info["reqStr"] == "":
                self.data_ready_callback(server_info["cmdList"], server_info["serverType"])

    def stop(self):
        self.continue_running = False

    def run(self):
        while self.continue_running:
            for server_info in self.automation_server_info:
                if server_info["reqStr"] != "":
                    # Check for separate room info needed
                    room_str = ""
                    if "roomReqStr" in server_info and server_info["roomReqStr"] != "":
                        roomUrl = server_info["baseUrl"] + server_info["roomReqStr"]
                        room_str = self.httpHandler.getTextResponse(roomUrl)
                    reqUrl = server_info["baseUrl"] + server_info["reqStr"]
                    resp_str = self.httpHandler.getTextResponse(reqUrl)
                    if len(resp_str) <= 0:
                        continue

#                    print ("Automation Manager Actions Received len = {0}".format(len(resp_str)))
                    self.rooms = self.getRooms(room_str if room_str != "" else resp_str, server_info)
                    self.actions = self.getActions(resp_str, self.rooms, server_info)
    #                self.actions.sort()
                    self.data_ready_callback(self.actions, server_info["serverType"])
            time.sleep(self.update_period_secs)

    def getRooms(self, resp_str, server_info):
        rooms = {}
        if server_info["serverType"] == "fibaro":
            try:
                roomsIntern = json.loads(resp_str)
                for roomInf in roomsIntern:
                    rooms[roomInf["id"]] = roomInf["name"]
            except:
                print("Failed to interpret fibaro rooms info")
        else:
            match_room = r".*?(<room\b.*?>)"
            matches = re.split(match_room, resp_str)
            for match in matches:
                if match[:6] == "<room ":
                    self.addRoom(rooms, match)
        return rooms

    def getAttrib(self, tagBody, tagId):
        reg = r'' + tagId + r'="(.*?)"'
        grp = re.search(reg, tagBody)
        if grp is None or grp.lastindex is None:
            return ""
        return grp.group(1)

    def getValue(self, tagBody):
        reg = r'>(.*?)<'
        grp = re.search(reg, tagBody)
        if grp is None or grp.lastindex is None:
            return ""
        return grp.group(1)

    def addRoom(self, rooms, tagBody):
        name = self.getAttrib(tagBody, "name")
        id = self.getAttrib(tagBody, "id")
        if id != "":
            rooms[id] = name

    def getActions(self, resp_str, rooms, server_info):
        actions = []
        if server_info["serverType"] == "fibaro":
            try:
                scenesIntern = json.loads(resp_str)
                for sceneInf in scenesIntern:
                    self.addFibaroAction(actions, sceneInf, rooms, server_info)
            except:
                print("Failed to interpret fibaro rooms info")
        else:
            # Try Vera first
            match_scene = r".*?(<scene\b.*?>)"
            matches = re.split(match_scene, resp_str)
            if len(matches) > 1:
                # Vera
                for match in matches:
                    if match[:7] == "<scene ":
                        self.addVeraAction(actions, match, rooms, server_info)
            else:
                # Indigo
                match_action = r".*?(<action\b.*?>.*?</action>)"
                matches = re.split(match_action, resp_str)
                for match in matches:
                    if match[:8] == "<action ":
                        self.addIndigoAction(actions, match, rooms, server_info)
        return actions

    def addVeraAction(self, actions, tagBody, rooms, server_info):
        serverUrlPrefix = "automation/api/v1.0/exec"
        name = self.getAttrib(tagBody, "name")
        iconName = ""
        id = self.getAttrib(tagBody, "id")
        roomId = self.getAttrib(tagBody, "room")
        roomName = ""
        if roomId in rooms:
            roomName = rooms[roomId]
        if id != "":
            cmdParam = serverUrlPrefix + "/_vera_" + id
            actions.append( { "actionNum" : id, "actionName" : name, "groupName" : roomName, "actionUrl" : cmdParam, "iconName": iconName, "urlPrefix": serverUrlPrefix } )

    def addIndigoAction(self, actions, tagBody, rooms, server_info):
        serverUrlPrefix = "automation/api/v1.0/exec"
        cmdParam = self.getAttrib(tagBody, "href")
        name = self.getValue(tagBody)
        iconName = ""
        cmdParam = serverUrlPrefix + "/_indigo_" + cmdParam
        if name != "":
            actions.append( { "actionNum" : "", "actionName" : name, "groupName" : "", "actionUrl" : cmdParam, "iconName": iconName, "urlPrefix": serverUrlPrefix } )

    def addFibaroAction(self, actions, sceneInf, rooms, server_info):
        serverUrlPrefix = "automation/api/v1.0/exec"
        id = sceneInf["id"]
        name = sceneInf["name"]
        roomId = sceneInf["roomID"]
        roomName = ""
        if roomId in rooms:
            roomName = rooms[roomId]
        iconName = "bulb-on"
        iconId = sceneInf["iconID"]
        if iconId == 1:
            iconName = "bulb-on"
        if iconId == 2:
            iconName = "bulb-on"
        if iconId == 3:
            iconName = "bulb-off"
        if id is not None:
            if server_info["controlPath"] != "sendDirect":
                cmdParam = serverUrlPrefix + "/_fibaro_" + str(id)
            else:
                # Tried to get this to work on Fibaro Home Center 2 but auth using username:password@url doesn't seem to work through jquery
                # Need to see if I can get Fibaro server to support any other kind of auth - have tried basic auth using base64 key but not succeeded so far
                cmdParam = server_info["baseUrl"] + server_info["cmdPrefix"] + str(id) + server_info["cmdSuffix"]
            actions.append( { "actionNum" : id, "actionName" : name, "groupName" : roomName, "actionUrl" : cmdParam, "iconName": iconName, "urlPrefix": serverUrlPrefix } )