Exemple #1
0
    def handleRestore(self, pab, devname):
        logger.info("Opcode 4 Restore - %s", devname)
        logPab(pab)
        localPath = tinames.devnameToLocal(devname)

        recNum = recordNumber(pab)
        oled.info("RESTORE %d:/%s", recNum, devname)

        if localPath is None:
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        if localPath not in self.openFiles:
            # pass as well
            self.sendErrorCode(EDVNAME)
            return

        try:
            open_file = self.openFiles[localPath]
            if open_file == None:
                self.sendErrorCode(EFILERR)
                return

            open_file.restore(pab)
            self.sendSuccess()

        except Exception as e:
            traceback.print_exc()
            self.sendErrorCode(EFILERR)
Exemple #2
0
    def handleSave(self, pab, devname):
        logger.info("Opcode 6 Save - %s", devname)
        logPab(pab)
        unix_name = tinames.devnameToLocal(devname)
        logger.debug("unix_name for program is %s", unix_name)

        if unix_name == "" or unix_name is None:
            self.sendErrorCode(EDVNAME)
            return

        oled.info("SAVE:/%s", devname)

        logger.debug("saving program to %s", unix_name)
        if self.parentExists(unix_name):
            self.sendSuccess()
            fdata = self.tipi_io.receive()
            logger.debug("received program image")
            try:
                if unix_name.lower().endswith(basicSuffixes):
                    prog_file = BasicFile.create(fdata)
                else:
                    prog_file = ProgramImageFile.create(devname, unix_name, fdata)
                logger.debug("created file object")
                prog_file.save(unix_name)

                self.sendSuccess()
            except Exception as e:
                logger.exception("failed to save PROGRAM")
                self.sendErrorCode(EDEVERR)
            return
        self.sendErrorCode(EDEVERR)
Exemple #3
0
    def handleWrite(self, pab, devname):
        logger.info("Opcode 3 Write - %s", devname)
        logPab(pab)
        localPath = tinames.devnameToLocal(devname)
        recNum = recordNumber(pab)
        oled.info("WRITE %d:/%s", recNum, devname)

        if localPath is None:
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        if localPath not in self.openFiles:
            # pass to a different device.
            self.sendErrorCode(EDVNAME)
            return

        try:
            open_file = self.openFiles[localPath]
            if open_file == None:
                self.sendErrorCode(EFILERR)
                return

            self.sendSuccess()
            bytes = self.tipi_io.receive()
            open_file.writeRecord(bytes, pab)
            self.sendSuccess()
            return

        except Exception as e:
            traceback.print_exc()
            self.sendErrorCode(EFILERR)

        self.sendErrorCode(EDEVERR)
Exemple #4
0
    def handleBind(self, bytes):
        serverId = bytes[1]
        params = str(bytes[3:]).split(':')
        interface = params[0]
        port = int(params[1])
        logger.info("bind socket(%d) %s:%d", serverId, interface, port)

        existing = self.bindings.get(serverId, None)
        # close the socket if we already had one for this handle.
        if existing is not None:
            del (self.bindings[serverId])
            self.safeClose(existing)
            existing = None
            logger.debug("closed leftover binding: %d", serverId)
        # need to get the target host and port
        if interface == "*":
            interface = '0.0.0.0'
        server = (interface, port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(0)
        try:
            sock.bind(server)
            self.bindings[serverId] = sock
            sock.listen(5)
            logger.info("bind success")
            oled.info("Socket %d/Bound", serverId)
            return GOOD
        except Exception:
            logger.info("failed to bind socket: %d", serverId, exc_info=True)
            self.safeClose(sock)
            return BAD
Exemple #5
0
    def handleOpen(self, bytes):
        handleId = bytes[1]
        params = str(bytes[3:]).split(':')
        hostname = params[0]
        port = int(params[1])
        logger.info("open socket(%d) %s:%d", handleId, hostname, port)

        existing = self.handles.get(handleId, None)
        # close the socket if we already had one for this handle.
        if existing is not None:
            del (self.handles[handleId])
            self.safeClose(existing)
            existing = None
            logger.debug("closed leftover socket: %d", handleId)
        # need to get the target host and port
        server = (hostname, port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.handles[handleId] = sock
        try:
            sock.connect(server)
            fcntl.fcntl(sock, fcntl.F_SETFL, os.O_NONBLOCK)
            logger.info("connected")
            oled.info("Socket %d/Connected", handleId)
            return GOOD
        except Exception:
            logger.info("failed to connect socket: %d",
                        handleId,
                        exc_info=True)
            self.safeClose(sock)
            return BAD
Exemple #6
0
 def handleClose(self, bytes):
     handleId = bytes[1]
     existing = self.handles.get(handleId, None)
     if existing is not None:
         del (self.handles[handleId])
         self.safeClose(existing)
         logger.info("closed socket: %d", handleId)
         oled.info("Socket %d/Closed", handleId)
     return GOOD
Exemple #7
0
 def handleUnbind(self, bytes):
     serverId = bytes[1]
     if serverId in self.bindings.keys():
         existing = self.bindings.get(serverId, None)
         del (self.bindings[serverId])
         self.safeClose(existing)
         logger.info("unbound socket: %d", serverId)
         oled.info("Socket %d/Unbound", serverId)
     return GOOD
Exemple #8
0
 def close(self, pab, devname):
     logger.info("close %s", devname)
     self.tipi_io.send([SUCCESS])
     oled.info("Reboot/PENDING...")
     # Give the TI a little time to complete the IO request.
     time.sleep(1.000)
     # let the TI know that the PI service is offline.
     TipiPorts.getInstance().setRC(0xFF)
     with open("/tmp/tipireboot", 'w') as fh_out:
         fh_out.write("woot")
     # Block forever, until we are killed and restarted.
     while True:
         time.sleep(2)
Exemple #9
0
 def handleWrite(self, bytes):
     handleId = bytes[1]
     if not handleId in self.handles.keys():
         logger.info("No socket open for handleId %s", handleId)
         return BAD
     try:
         existing = self.handles[handleId]
         existing.sendall(bytes[3:])
         logger.debug("wrote %d bytes to socket: %d", len(bytes[3:]),
                      handleId)
         oled.info("Socket %d/Wrote %d bytes", handleId, len(bytes[3:]))
         return GOOD
     except Exception:
         del (self.handles[handleId])
         self.safeClose(existing)
         logger.info("failed to write to socket: %d", handleId)
         return BAD
Exemple #10
0
    def handleLoad(self, pab, devname):
        logger.info("Opcode 5 LOAD - %s", devname)
        logPab(pab)
        maxsize = recordNumber(pab)
        unix_name = tinames.devnameToLocal(devname)

        if unix_name is None or not os.path.exists(unix_name):
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return
        try:
            oled.info("LOAD:/%s", devname)
            if (not ti_files.isTiFile(unix_name)) and unix_name.lower().endswith(basicSuffixes):
                prog_file = BasicFile.load(unix_name)
            else:
                prog_file = ProgramImageFile.load(unix_name)

            filesize = prog_file.getImageSize()
            bytes = prog_file.getImage()
            if filesize > maxsize:
                logger.debug("TI buffer too small, only loading %d of %d bytes", maxsize, filesize)
                bytes = bytes[:maxsize]

            dirname = os.path.dirname(unix_name)
            if tipi_config.get("AUTO") == "on":
                tipidirname = tinames.local2tipi(dirname)
                logger.debug("tmp mapping DSK1 to %s", tipidirname)
                tipi_config.settmp("DSK1_DIR", tipidirname)
            else:
                logger.debug("AUTO mapping not enabled")

            tipifile = os.path.join(dirname, "TIPI")
            if os.path.isfile(tipifile):
                config_records = load_internal(tipifile)
                tipi_config.applyrecords(config_records)

            self.sendSuccess()
            logger.info("LOAD image size %d", filesize)
            self.tipi_io.send(bytes)

        except Exception as e:
            # I don't think this will work. we need to check for as
            #   many errors as possible up front.
            self.sendErrorCode(EFILERR)
            logger.exception("failed to load file - %s", devname)
Exemple #11
0
 def handle(self, pab, devname):
     logger.debug("Matching special file handler for: %s", devname)
     if devname.startswith(("URI1.", "URI2.", "URI3.")):
         uriShortcut = str(devname[:4])
         link = tipi_config.get(uriShortcut)
         if link != "":
             devname = "PI." + link + "/" + devname[5:]
             logger.debug("using %s to map to %s", uriShortcut, devname)
     if devname.startswith("PI."):
         fname = str(devname[3:])
         logger.debug("Looking for special file handler: %s", fname)
         for prefix in self.specreg.keys():
             if fname.startswith(prefix):
                 oled.info("Accessing/%s", fname)
                 handler = self.specreg.get(prefix, None)
                 handler.handle(pab, devname)
                 return True
     return False
Exemple #12
0
    def handleDelete(self, pab, devname):
        logger.info("Opcode 7 Delete - %s", devname)
        logPab(pab)

        unix_name = tinames.devnameToLocal(devname)
        if unix_name is None:
            self.sendErrorCode(EDVNAME)
            return

        oled.info("DELETE:/%s", devname)

        logger.debug("deleting file %s", unix_name)
        try:
            del self.openFiles[unix_name]
        except Exception as e:
            logger.debug("removing open file on delete: file was not open! Good")
        try:
            os.unlink(unix_name)
            self.sendSuccess()
        except Exception as e:
            logger.exception("failed to delete a file")
            self.sendErrorCode(EDEVERR)
Exemple #13
0
    def handleStatus(self, pab, devname):
        logger.info("Opcode 9 Status - %s", devname)
        logPab(pab)
        statbyte = 0

        unix_name = tinames.devnameToLocal(devname)
        if unix_name is None:
            self.sendErrorCode(EDVNAME)
            return

        if not os.path.exists(unix_name):
            statbyte |= STNOFILE
        else:
            if not os.path.isdir(unix_name):
                open_file = None
                try:
                    open_file = self.openFiles[unix_name]
                except:
                    pass
                if open_file is not None:
                    statbyte = open_file.getStatusByte()
                else:
                    if ti_files.isTiFile(unix_name):
                        fh = open(unix_name, "rb")
                        header = bytearray(fh.read())[:128]
                        if ti_files.isVariable(header):
                            statbyte |= STVARIABLE
                        if ti_files.isProgram(header):
                            statbyte |= STPROGRAM
                        if ti_files.isInternal(header):
                            statbyte |= STINTERNAL
                    else:
                        statbyte = NativeFile.status(unix_name)

        oled.info("STATUS %d:/%s", statbyte, devname)

        self.tipi_io.send([SUCCESS])
        self.tipi_io.send([statbyte])
Exemple #14
0
 def handleRead(self, bytes):
     try:
         handleId = bytes[1]
         logger.debug("read socket: %d", handleId)
         existing = self.handles.get(handleId, None)
         if existing is None:
             logger.info("socket not open: %d", handleId)
             return bytearray(0)
         limit = (bytes[3] << 8) + bytes[4]
         data = bytearray(existing.recv(limit))
         logger.info("read %d bytes from %d", len(data), handleId)
         oled.info("Socket %d/Read %d bytes", handleId, len(data))
         return data
     except socket.error as e:
         err = e.args[0]
         if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
             logger.debug("no data ready: %d", handleId)
             return bytearray(0)
         else:
             logger.error(e, exc_info=True)
     except Exception as e:
         logger.error(e, exc_info=True)
     return BAD
Exemple #15
0
    def handleRead(self, pab, devname):
        logger.debug("Opcode 2 Read - %s", devname)
        logPab(pab)
        localPath = tinames.devnameToLocal(devname)
        recNum = recordNumber(pab)
        oled.info("READ %d:/%s", recNum, devname)

        if localPath is None:
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        if localPath not in self.openFiles:
            # pass to a different device.
            self.sendErrorCode(EDVNAME)
            return

        try:
            open_file = self.openFiles[localPath]

            if not open_file.isLegal(pab):
                logger.error("illegal read mode for %s", devname)
                self.sendErrorCode(EFILERR)
                return

            rdata = open_file.readRecord(recNum)
            if rdata is None:
                logger.debug("received None for record %d", recNum)
                self.sendErrorCode(EEOF)
            else:
                self.sendSuccess()
                self.tipi_io.send(rdata)
            return
        except Exception as e:
            traceback.print_exc()
            self.sendErrorCode(EFILERR)
Exemple #16
0
    def handleClose(self, pab, devname):
        logger.debug("Opcode 1 Close - %s", devname)
        oled.info("CLOSE:/%s", devname)
        logPab(pab)
        localPath = tinames.devnameToLocal(devname)

        if localPath is None:
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        if localPath not in self.openFiles:
            # not open by us, maybe some other controller handled it.
            self.sendErrorCode(EDVNAME)
            return

        try:
            open_file = self.openFiles[localPath]
            open_file.close(localPath)
            del self.openFiles[localPath]
            self.sendSuccess()
        except Exception as e:
            self.sendErrorCode(EFILERR)
            pass
Exemple #17
0
                                                  maxBytes=(1000 * 1024),
                                                  backupCount=2)
logformatter = logging.Formatter(
    '%(asctime)-15s %(name)-12s: %(levelname)-8s %(message)s')
loghandler.setFormatter(logformatter)
logging.getLogger('').addHandler(loghandler)

__name__ = "TipiService"

logger = logging.getLogger(__name__)

##
# MAIN
##
try:
    oled.info("TIPI Init")

    tipi_io = TipiMessage()
    specialFiles = SpecialFiles(tipi_io)
    rawExtensions = RawExtensions(tipi_io)
    levelTwo = LevelTwo(tipi_io)
    tipiDisk = TipiDisk(tipi_io)

    oled.info("TIPI Ready")
    logger.info("TIPI Ready")
    while True:
        logger.debug("waiting for request...")
        try:
            msg = tipi_io.receive()
        except BackOffException:
            if os.path.exists('/tmp/tipi_safepoint'):
Exemple #18
0
 def close(self, pab, devname):
     logger.info("close %s", devname)
     self.tipi_io.send([SUCCESS])
     oled.info("Shutdown/PENDING...")
     with open("/tmp/tipihalt", 'w') as fh_out:
         fh_out.write("woot")
Exemple #19
0
    def handleOpen(self, pab, devname):
        logger.info("Opcode 0 Open - %s", devname)
        oled.info("OPEN:/%s", devname)
        logPab(pab)
        localPath = tinames.devnameToLocal(devname)
        if localPath is None:
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        logger.debug("  local file: " + localPath)
        if mode(pab) == INPUT and not os.path.exists(localPath):
            logger.info("Passing to other controllers")
            self.sendErrorCode(EDVNAME)
            return

        if os.path.isdir(localPath):
            try:
                cat_file = CatalogFile.load(localPath, pab, devname)
                self.sendSuccess()
                self.tipi_io.send([cat_file.getRecordLength()])
                self.openFiles[localPath] = cat_file
                return
            except Exception as e:
                self.sendErrorCode(EOPATTR)
                logger.exception("failed to open dir - %s", devname)
                return

        if os.path.exists(localPath):
            try:
                if ti_files.isTiFile(localPath):
                    if recordType(pab) == FIXED:
                        open_file = FixedRecordFile.load(localPath, pab)
                    else:
                        open_file = VariableRecordFile.load(localPath, pab)
                else:
                    open_file = NativeFile.load(localPath, pab)

                if open_file is None:
                    self.sendErrorCode(EOPATTR)
                    return

                fillInRecordLen = open_file.getRecordLength()

                self.sendSuccess()
                self.tipi_io.send([fillInRecordLen])
                self.openFiles[localPath] = open_file
                return

            except Exception as e:
                self.sendErrorCode(EOPATTR)
                logger.error("failed to open file - %s", devname)
                return


        else:
            if self.parentExists(localPath):
                if recordType(pab) == VARIABLE:
                    open_file = VariableRecordFile.create(devname, localPath, pab)
                else:
                    open_file = FixedRecordFile.create(devname, localPath, pab)
                self.openFiles[localPath] = open_file
                self.sendSuccess()
                self.tipi_io.send([open_file.getRecordLength()])
                return
            else:
                # EDEVERR triggers passing on the pab request to other controllers.
                self.sendErrorCode(EDVNAME)
                return

        self.sendErrorCode(EFILERR)