예제 #1
0
    def round_trip32(self, nnn):
        """
        Test writing and reading a 32-bit integer as the first and
        only field in a buffer.
        """
        chan = Channel(LEN_BUFF)

        # -- write 32-bit value -------------------------------------
        field_nbr = 1 + self.rng.next_int16(1024)
        write_b32_field(chan, nnn, field_nbr)
        chan.flip()

        # -- read 32-bit value --------------------------------------
        # first the header (which is a varint) ------------
        (field_type, field_nbr2) = read_field_hdr(chan)
        offset2 = chan.position
        self.assertEqual(PrimTypes.B32, field_type)
        self.assertEqual(field_nbr, field_nbr2)
        self.assertEqual(
            length_as_varint(field_hdr_val(field_nbr, PrimTypes.B32)), offset2)

        # then the varint proper --------------------------
        varint_ = read_raw_b32(chan)
        offset3 = chan.position
        self.assertEqual(nnn, varint_)
        self.assertEqual(offset2 + 4, offset3)
예제 #2
0
    def round_trip64(self, nnn):
        """
        Test writing and reading a 64-bit integer as the first and
        only field in a buffer
        """
        chan = Channel(LEN_BUFF)

        # -- write 64-bit value -------------------------------------
        field_nbr = 1 + self.rng.next_int16(1024)
        write_b64_field(chan, nnn, field_nbr)
        chan.flip()

        #       # DEBUG
        #       buf = chan.buffer
        #       print "buffer after writing varint field: ",
        #       dumpBuffer(buf)
        #       # END

        # -- read 64-bit value --------------------------------------
        # first the header (which is a varint) ------------
        (field_type, field_nbr2) = read_field_hdr(chan)
        offset2 = chan.position
        self.assertEqual(PrimTypes.B64, field_type)
        self.assertEqual(field_nbr, field_nbr2)
        self.assertEqual(
            length_as_varint(field_hdr_val(field_nbr, PrimTypes.B64)), offset2)

        # then the varint proper --------------------------
        varint_ = read_raw_b64(chan)
        offset3 = chan.position
        self.assertEqual(nnn, varint_)
        self.assertEqual(offset2 + 8, offset3)
예제 #3
0
    def round_trip(self, nnn):
        """
        Test writing and reading a varint as the first and
        only field in a buffer.
        """
        # -- write varint -------------------------------------------
        field_nbr = 1 + self.rng.next_int16(1024)
        chan = Channel(LEN_BUFFER)
        write_varint_field(chan, nnn, field_nbr)
        chan.flip()

        # -- read varint --------------------------------------------
        # first the header (which is a varint) ------------
        (prim_type, field_nbr2) = read_field_hdr(chan)
        offset2 = chan.position
        self.assertEqual(PrimTypes.VARINT, prim_type)
        self.assertEqual(field_nbr, field_nbr2)
        self.assertEqual(length_as_varint(field_nbr << 3), offset2)

        # then the varint proper --------------------------
        varint_ = read_raw_varint(chan)
        chan.flip()
        offset3 = chan.limit
        self.assertEqual(nnn, varint_)
        self.assertEqual(offset2 + length_as_varint(nnn), offset3)
예제 #4
0
    def round_trip(self, string):
        """
        Verify that a unicode string converted to wire format and then
        back again is the same string.

        This tests writing and reading a string of bytes as the first and
        only field in a buffer.
        """
        chan = Channel(LEN_BUFF)

        # -- write the bytearray ------------------------------------
        field_nbr = 1 + self.rng.next_int16(1024)
        write_len_plus_field(chan, string, field_nbr)
        chan.flip()

#       # DEBUG
#       print("buffer after writing lenPlus field: " + str(chan.buffer))
#       # END

        # -- read the value written ---------------------------------
        # first the header (which is a varint) ------------
        (field_type, field_nbr2,) = read_field_hdr(chan)
        offset2 = chan.position
        self.assertEqual(PrimTypes.LEN_PLUS, field_type)
        self.assertEqual(field_nbr, field_nbr2)
        self.assertEqual(
            length_as_varint(field_hdr_val(field_nbr, PrimTypes.LEN_PLUS)),
            offset2)

        # then the actual value written -------------------
        tstamp = read_raw_len_plus(chan)
        offset3 = chan.position
        self.assertEqual(string, tstamp)
        self.assertEqual(
            offset2 +
            length_as_varint(
                len(string)) +
            len(string),
            offset3)
예제 #5
0
    def test_ring_data_proto_serialization(self):
        str_obj_model = self.make_str_obj_model()
        proto_name = str_obj_model.name
        outer_msg_spec = str_obj_model.msgs[0]
        inner_msg_spec = str_obj_model.msgs[0].msgs[0]
        outer_msg_cls = make_msg_class(str_obj_model, outer_msg_spec.name)
        # NOTE change in parent
        inner_msg_cls = make_msg_class(outer_msg_spec, inner_msg_spec.name)

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing # the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create a message instance ---------------------------------

        # create some HostInfo instances
        count = 2 + RNG.next_int16(7)  # so 2 .. 8
        ring = []
        for nnn in range(count):
            # should avoid dupes
            values = host_info_values()
            ring.append(inner_msg_cls(values))

        outer_msg = outer_msg_cls([ring])     # a list whose member is a list

        # serialize the object to the channel -----------------------
        nnn = outer_msg.write_stand_alone(chan)

        old_position = chan.position
        chan.flip()
        self.assertEqual(old_position, chan.limit)
        self.assertEqual(0, chan.position)

        # deserialize the channel, making a clone of the message ----
        (read_back, nn2) = outer_msg_cls.read(chan, str_obj_model)
        self.assertIsNotNone(read_back)

        # verify that the messages are identical --------------------
        self.assertTrue(outer_msg.__eq__(read_back))
        self.assertEqual(nnn, nn2)

        # produce another message from the same values --------------
        outer_msg2 = outer_msg_cls([ring])
        chan2 = Channel(BUFSIZE)
        nnn = outer_msg2.write_stand_alone(chan2)
        chan2.flip()
        (copy2, nn3) = outer_msg_cls.read(chan2, str_obj_model)
        self.assertTrue(outer_msg.__eq__(copy2))
        self.assertTrue(outer_msg2.__eq__(copy2))                   # GEEP
예제 #6
0
    def test_zoggery_serialization(self):
        # XXX These comments are generally out of date.

        # Testing MsgSpec with simple fields.  Verify that getter,
        # putter, lenFunc, and pLenFunc work for the basic types
        # (ie, that they are correctly imported into this reg) and
        # they are work for the newly defined single-msg protoSpec.

        # Use ZOGGERY_PROTO_SPEC

        # parse the protoSpec
        # verify that this adds 1 (msg) + 5 (field count) to the number
        # of entries in getters, putters, etc

        self.assertIsNotNone(self.str_obj_model)
        self.assertTrue(isinstance(self.str_obj_model, M.ProtoSpec))
        self.assertEqual('org.xlattice.zoggery', self.str_obj_model.name)

        self.assertEqual(len(self.str_obj_model.enums), 0)
        self.assertEqual(len(self.str_obj_model.msgs), 1)
        self.assertEqual(len(self.str_obj_model.seqs), 0)

        msg_spec = self.str_obj_model.msgs[0]
        msg_name = msg_spec.name
        self.assertEqual('logEntry', msg_name)

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing # the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create the LogEntryMsg class ------------------------------
        log_entry_msg_cls = make_msg_class(self.str_obj_model, msg_name)

        # DEBUG
        print("testZoggery: LogEntryMsg is of type ", type(log_entry_msg_cls))
        # END

        # create a message instance ---------------------------------
        values = self.le_msg_values()        # a list of quasi-random values
        le_msg = log_entry_msg_cls(values)

        # DEBUG
        print("type of LogEntryMsg: ", type(log_entry_msg_cls))
        print("type of leMsg:       ", type(le_msg))
        # END

        self.assertTrue(isinstance(le_msg, log_entry_msg_cls))

        (timestamp, key, length, node_id, by_, path) = tuple(values)

        # F A I L S:
        #   msg_spec.name is 'logEntry'
        #   le_msg._name is  '[148639516, [227, 217, ...[230 chars].gz']
        self.assertEqual(msg_spec.name, le_msg._name)
        # we don't have any nested enums or messages

        # XXX FAIL: properties have no len()
        # self.assertEqual(0, len(leMsg.enums))

        # DEBUG
        print("leMsg.enums: ", le_msg.enums)
        # END

        # self.assertEqual(0, len(leMsg.msgs))

        self.assertEqual(6, len(le_msg.field_classes))
        self.assertEqual(6, len(le_msg))        # number of fields in instance
        for i in range(len(le_msg)):
            # DEBUG
            print("value %d is %s" % (i, values[i]))

            # FAILS: is a PROPERTY OBJECT
            print("leMsg %d is %s" % (i, le_msg[i].value))
            # END
            self.assertEqual(values[i], le_msg[i].value)         # FAILS

        # verify fields are accessible in the object ----------------
        (timestamp, node_id, key, length, by_, path) = tuple(values)
        self.assertEqual(timestamp, le_msg.timestamp)
        self.assertEqual(node_id, le_msg.node_id)
        self.assertEqual(key, le_msg.key)
        self.assertEqual(length, le_msg.length)
        self.assertEqual(by_, le_msg.by_)
        self.assertEqual(path, le_msg.path)

        # serialize the object to the channel -----------------------
        buf = chan.buffer
        chan.clear()
        nnn = le_msg.write_stand_alone(chan)
        self.assertEqual(0, nnn)
        old_position = chan.position                     # TESTING flip()
        chan.flip()
        self.assertEqual(old_position, chan.limit)      # TESTING flip()
        self.assertEqual(0, chan.position)   # TESTING flip()
        actual = chan.limit

        print("ACTUAL LENGTH OF SERIALIZED OBJECT: %u" % actual)

        # deserialize the channel, making a clone of the message ----
        (read_back, nn2) = MsgImpl.read(chan, self.str_obj_model)
        self.assertIsNotNone(read_back)
        self.assertTrue(le_msg.__eq__(read_back))

        # produce another message from the same values --------------
        le_msg2 = log_entry_msg_cls(values)
        chan2 = Channel(BUFSIZE)
        nnn = le_msg2.write_stand_alone(chan2)
        chan2.flip()
        (copy2, nn3) = log_entry_msg_cls.read(chan2, self.str_obj_model)
        self.assertTrue(le_msg.__eq__(read_back))
        self.assertTrue(le_msg2.__eq__(copy2))
        self.assertEqual(nnn, nn3)
예제 #7
0
    def test_the_daemon(self):
        chan = Channel(BUFSIZE)
        chan.clear()  # XXX should be guaranteed on new channel

        msg_count = 8 + RNG.next_int16(25)  # so 8..32
        # DEBUG
        print("MSG_COUNT = %u" % msg_count)
        # END

        # set up options ----------------------------------
        now = int(time.time())
        pgm_name_and_version = "testWithDummyClient v%s %s" % (
            __version__, __version_date__)
        with open('/etc/hostname', 'r') as file:
            this_host = file.read().strip()

        options = {}  # a namespace, so to speak
        options['ec2Host'] = False
        options['justShow'] = False
        options['log_dir'] = 'logs'
        options['pgm_name_and_version'] = pgm_name_and_version
        options['port'] = 55555
        options['showTimestamp'] = False
        options['showVersion'] = False
        options['testing'] = True
        options['this_host'] = this_host
        options['timestamp'] = now
        options['verbose'] = False
        ns_ = Namespace(options)

        # clear the log files (so delete any files under logs/) -----
        self.do_clear_logs(ns_)

        # start the daemon --------------------------------
        daemon_t = threading.Thread(target=run_the_daemon, args=(ns_, ))
        daemon_t.start()

        # give the daemon time to wake up  --------------------------
        time.sleep(0.15)  # XXX without this we get an abort saying
        # that libev cannot allocate (2G - 16)B

        # start sending (some fixed number of ) messages ------------
        msgs_sent = []
        for nnn in range(msg_count):
            msg = self.next_zone_mismatch_msg()
            seq_nbr_field = msg[1]
            # XXX by name would be better!
            self.assertEqual(nnn, seq_nbr_field.value)

            # serialize msg into the channel
            chan.clear()
            msg.write_stand_alone(chan)
            chan.flip()

            # send the msg to the daemon ------------------
            skt = send_to_end_point(chan, '127.0.0.1', 55555)
            time.sleep(0.05)
            skt.close()
            msgs_sent.append(msg)

            # DEBUG
            print("MSG %d HAS BEEN SENT" % nnn)
            # END

        self.assertEqual(msg_count, len(msgs_sent))

        # delay a few ms --------------------------------------------
        time.sleep(0.05)

        # build and send shutdown msg -------------------------------
        msg = self.next_shutdown_msg()
        chan.clear()
        msg.write_stand_alone(chan)
        chan.flip()

        skt = send_to_end_point(chan, '127.0.0.1', 55555)
        # DEBUG
        print("SHUTDOWN MSG HAS BEEN SENT")
        # END

        # delay a few ms --------------------------------------------
        time.sleep(0.05)
        skt.close()

        # join the daemon thread ------------------------------------
        time.sleep(0.05)
        daemon_t.join()
예제 #8
0
    def test_little_big(self):
        self.assertIsNotNone(self.str_obj_model)
        self.assertTrue(isinstance(self.str_obj_model, M.ProtoSpec))
        self.assertEqual('org.xlattice.fieldz.test.littleBigProto',
                         self.str_obj_model.name)

        self.assertEqual(0, len(self.str_obj_model.enums))
        self.assertEqual(1, len(self.str_obj_model.msgs))
        self.assertEqual(0, len(self.str_obj_model.seqs))

        msg_spec = self.str_obj_model.msgs[0]

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create the LittleBigMsg class ------------------------------
        little_big_msg_cls = make_msg_class(self.str_obj_model, msg_spec.name)

        # -------------------------------------------------------------
        # XXX the following fails because field 2 is seen as a property
        # instead of a list
        if False:        # DEBUGGING
            print('\nLittleBigMsg CLASS DICTIONARY')
            for (ndx, key) in enumerate(little_big_msg_cls.__dict__.keys()):
                print(
                    "%3u: %-20s %s" %
                    (ndx, key, little_big_msg_cls.__dict__[key]))
        # -------------------------------------------------------------

        # create a message instance ---------------------------------
        values = self.lil_big_msg_values()            # quasi-random values
        lil_big_msg = little_big_msg_cls(values)

        # __setattr__ in MetaMsg raises exception on any attempt
        # to add new attributes.  This works at the class level but
        # NOT at the instance level
        #
        if True:
            try:
                lil_big_msg.foo = 42
                self.fail(
                    "ERROR: attempt to assign new instance attribute succeeded")
            except AttributeError as a_exc:
                # DEBUG
                print(
                    "ATTR ERROR ATTEMPTING TO SET lilBigMsg.foo: " +
                    str(a_exc))
                # END
                pass

        if '__dict__' in dir(lil_big_msg):
            print('\nlilBigMsg INSTANCE DICTIONARY')
            for exc in list(lil_big_msg.__dict__.keys()):
                print("%-20s %s" % (exc, lil_big_msg.__dict__[exc]))

        # lilBigMsg.name is a property
        try:
            lil_big_msg.name = 'boo'
            self.fail("ERROR: attempt to change message name succeeded")
        except AttributeError:
            pass

        self.assertEqual(msg_spec.name, lil_big_msg.name)
        # we don't have any nested enums or messages
        self.assertEqual(0, len(lil_big_msg.enums))
        self.assertEqual(0, len(lil_big_msg.msgs))

        self.assertEqual(17, len(lil_big_msg.field_classes))
        # number of fields in instance
        self.assertEqual(17, len(lil_big_msg))
        for i in range(len(lil_big_msg)):
            self.assertEqual(values[i], lil_big_msg[i].value)

        # serialize the object to the channel -----------------------
        print("\nDEBUG: PHASE A ######################################")
        nnn = lil_big_msg.write_stand_alone(chan)

        old_position = chan.position
        chan.flip()
        self.assertEqual(old_position, chan.limit)
        self.assertEqual(0, chan.position)

        # deserialize the channel, making a clone of the message ----
        (read_back, nn2) = little_big_msg_cls.read(
            chan, self.str_obj_model)  # sOM is protoSpec
        self.assertIsNotNone(read_back)
        self.assertEqual(nnn, nn2)

        # verify that the messages are identical --------------------
        self.assertTrue(lil_big_msg.__eq__(read_back))

        print("\nDEBUG: PHASE B ######################################")
        # produce another message from the same values --------------
        lil_big_msg2 = little_big_msg_cls(values)
        chan2 = Channel(BUFSIZE)
        nnn = lil_big_msg2.write_stand_alone(chan2)
        chan2.flip()
        (copy2, nn3) = little_big_msg_cls.read(chan2, self.str_obj_model)
        self.assertIsNotNone(copy2)
        self.assertEqual(nnn, nn3)
        self.assertTrue(lil_big_msg.__eq__(copy2))
        self.assertTrue(lil_big_msg2.__eq__(copy2))

        # test clear()
        chan2.position = 97
        chan2.limit = 107
        chan2.clear()
        self.assertEqual(0, chan2.limit)
        self.assertEqual(0, chan2.position)
예제 #9
0
    def test_msg_impl(self):
        self.assertIsNotNone(self.str_obj_model)
        self.assertTrue(isinstance(self.str_obj_model, M.ProtoSpec))
        self.assertEqual('org.xlattice.zoggery', self.str_obj_model.name)

        self.assertEqual(0, len(self.str_obj_model.enums))
        self.assertEqual(1, len(self.str_obj_model.msgs))
        self.assertEqual(0, len(self.str_obj_model.seqs))

        msg_spec = self.str_obj_model.msgs[0]

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing # the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create the LogEntryMsg class ------------------------------

        log_entry_msg_cls = make_msg_class(self.str_obj_model, msg_spec.name)

        # __setattr__ in MetaMsg raises exception on any attempt
        # to add new attributes

        # TEST TEMPORARILY DISABLED
#        try:
#            LogEntryMsg.foo = 42
#            self.fail(
#                "ERROR: attempt to assign new class attribute succeeded")
#        except AttributeError as ae:
#
#            # DEBUG
#            print(
#                "success: attr error attempting to set LogEntryMsg.foo: " +
#                str(ae))
#            # END
#            pass                # GEEP

        # create a message instance ---------------------------------
        values = self.le_msg_values()            # quasi-random values
        le_msg = log_entry_msg_cls(values)

        # __setattr__ in MetaMsg raises exception on any attempt
        # to add new attributes.  This works at the class level but
        # NOT at the instance level
        if False:
            try:
                le_msg.foo = 42
                self.fail(
                    "ERROR: attempt to assign new instance attribute succeeded")
            except AttributeError as a_exc:
                # DEBUG
                print("ATTR ERROR ATTEMPTING TO SET leMsg.foo: " + str(a_exc))
                # END
                # pass

        # leMsg._name is a property
        # TEST TEMPORARILY DISABLED
#        try:
#            leMsg._name = 'boo'
#            self.fail("ERROR: attempt to change message name succeeded")
#        except AttributeError:
#            pass

        self.assertEqual(msg_spec.name, le_msg._name)
        # we don't have any nested enums or messages
        self.assertEqual(0, len(le_msg.enums))
        self.assertEqual(0, len(le_msg.msgs))

        self.assertEqual(6, len(le_msg.field_classes))
        self.assertEqual(6, len(le_msg))        # number of fields in instance
        # TEST TEMPORARILY DISABLED
#        for i in range(len(leMsg)):
#            self.assertEqual(values[i], leMsg[i].value)

        ################################
        # XXX FIELDS ARE NOT AS EXPECTED
        ################################

        # verify fields are accessible in the object ----------------
        # DEBUG
        for field in le_msg._fieldClasses:
            print("FIELD: %s = %s " % (field.name, field.value))
        # END
        (timestamp, node_id, key, length, by_, path) = tuple(values)
        # FAILS: null timestamp
        self.assertEqual(timestamp, le_msg.timestamp)

        self.assertEqual(node_id, le_msg.node_id)
        self.assertEqual(key, le_msg.key)
        self.assertEqual(length, le_msg.length)
        self.assertEqual(by_, le_msg.by_)
        self.assertEqual(path, le_msg.path)

        # serialize the object to the channel -----------------------
        # XXX not a public method
        expected_msg_len = le_msg._wire_len()
        print("EXPECTED LENGTH OF SERIALIZED OBJECT: %u" % expected_msg_len)
        buf = chan.buffer

        chan.clear()

        nnn = le_msg.write_stand_alone(chan)                 # n is class index
        old_position = chan.position                     # TESTING flip()
        chan.flip()
        self.assertEqual(old_position, chan.limit)      # TESTING flip()
        self.assertEqual(0, chan.position)   # TESTING flip()
        actual = chan.limit

        # deserialize the channel, making a clone of the message ----
        # XXX FAILS BECAUSE HEADER IS PRESENT:
        #(readBack,n2) = LogEntryMsg.read(chan, self.sOM)
        (read_back, nn2) = MsgImpl.read(chan, self.str_obj_model)
        self.assertIsNotNone(read_back)
        self.assertTrue(le_msg.__eq__(read_back))
        self.assertEqual(nnn, nn2)

        # produce another message from the same values --------------
        le_msg2 = log_entry_msg_cls(values)
        chan2 = Channel(BUFSIZE)
        nnn = le_msg2.write_stand_alone(chan2)
        chan2.flip()
        (copy2, nn3) = log_entry_msg_cls.read(chan2, self.str_obj_model)
        self.assertTrue(le_msg.__eq__(copy2))
        self.assertTrue(le_msg2.__eq__(copy2))
예제 #10
0
def _actually_run_the_daemon(options):
    verbose = options.verbose
    chan = Channel(BUFSIZE)
    string = None
    (cnx, addr) = (None, None)
    string = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    string.bind(('', options.port))
    string.listen(1)
    try:
        running = True
        while running:
            print("\nWAITING FOR CONNECTION")              # DEBUG
            cnx, addr = string.accept()
            try:
                accept_msg = "CONNECTION FROM %s" % str(addr)
                if verbose:
                    print(accept_msg)
                print("BRANCH TO options.accessLog.log()")
                sys.stdout.flush()
                options.access_log.log(accept_msg)
                print("BACK FROM options.access.log()")
                sys.stdout.flush()

                while 1:
                    chan.clear()

#                   print "BRANCH TO recvFromCnx"  ; sys.stdout.flush()
                    msg_ndx = recv_from_cnx(cnx, chan)  # may raise exception

                    (msg, _) = MsgImpl.read(chan, STR_OBJ_MODEL)
#                   print "  MSG_NDX: CALCULATED %s, REAL %s" % (
#                                             msgNdx, realNdx)
                    # switch on message type
                    if msg_ndx == 0:
                        print("GOT ZONE MISMATCH MSG")
                        # pylint: disable=no-member
                        print("    timestamp      %s" % msg.timestamp)
                        print("    seqNbr         %s" % msg.seq_nbr)
                        print("    zoneName       %s" % msg.zone_name)
                        print("    expectedSerial %s" % msg.expected_serial)
                        print("    actualSerial   %s" % msg.actual_serial)
                        text =\
                            "mismatch, domain %s: expected serial %s, got %s" % (
                                msg.zone_name, msg.expected_serial, msg.actual_serial)
                        options.alertz_log.log(text)

                    elif msg_ndx == 1:
                        # timestamp, seqNb
                        print("GOT CORRUPT LIST MSG")
                        # pylint: disable=no-member
                        print("    timestamp      %s" % msg.timestamp)
                        print("    seqNbr         %s" % msg.seq_nbr)
                        text = "corrupt list: %s" % (msg.seq_nbr)
                        options.alertz_log.log(text)

                    elif msg_ndx == 2:
                        # has one field, remarks
                        print("GOT SHUTDOWN MSG")
                        # pylint: disable=no-member
                        print("    remarks        %s" % msg.remarks)
                        running = False
                        string.close()
                        # XXX STUB: log the message
                        text = "shutdown: %s" % (msg.remarks)
                        options.alertz_log.log(text)

                    cnx.close()
                    break                   # permit only one message/cnx

            except KeyboardInterrupt:
                print("<keyboard interrupt received while connection open>")
                if cnx:
                    cnx.close()
                running = False

    except KeyboardInterrupt:
        print("<keyboard interrupt received while listening>")
        # listening socket will be closed
    finally:
        if cnx:
            cnx.close()
        if string:
            string.close()

        # COMMENTING THIS OUT PREVENTS SEGFAULT ON STOCKTON ---------
#       if options.logMgr is not None:
#           options.logMgr.close()
#           options.logMgr = None
        # END COMMENTING OUT ----------------------------------------

        if options.lock_mgr is not None:
            options.lock_mgr.unlock()
            options.lock_mgr = None
예제 #11
0
    def test_zone_mismatch_msg(self):
        # DEBUG
        print("\nTEST_ZONE_MISMATCH_MSG")
        # END

        # from setUp(): =============================================

        # end stuff from setup ======================================

        # -----------------------------------------------------------
        # XXX This code has been crudely hacked from another test
        # module, and so needs careful review
        # -----------------------------------------------------------

        # verify that this adds 1 (msg) + 3 (field count) to the number
        # of entries in getters, putters, etc

        self.assertIsNotNone(self.str_obj_model)
        self.assertTrue(isinstance(self.str_obj_model, M.ProtoSpec))
        self.assertEqual('org.xlattice.alertz', self.str_obj_model.name)

        self.assertEqual(0, len(self.str_obj_model.enums))
        self.assertEqual(16, len(self.str_obj_model.msgs))
        self.assertEqual(0, len(self.str_obj_model.seqs))

        msg_spec = self.str_obj_model.msgs[0]
        msg_name = msg_spec.name
        self.assertEqual('zoneMismatch', msg_name)

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing # the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create the ZoneMismatchMsg class ------------------------------
        zone_mismatch_msg_cls = make_msg_class(self.str_obj_model, msg_name)

        # create a message instance ---------------------------------
        values = self.zone_mismatch_fields()  # list of quasi-random values
        zmm_msg = zone_mismatch_msg_cls(values)

        self.assertEqual(msg_spec.name, zmm_msg.name)
        # we don't have any nested enums or messages
        # pylint: disable=no-member
        self.assertEqual(0, len(zmm_msg.enums))
        self.assertEqual(0, len(zmm_msg.msgs))

        self.assertEqual(5, len(zmm_msg.field_classes))
        self.assertEqual(5, len(zmm_msg))  # number of fields in instance
        self.assertEqual(values[0], zmm_msg.timestamp)
        self.assertEqual(values[1], zmm_msg.seq_nbr)
        self.assertEqual(values[2], zmm_msg.zone_name)
        self.assertEqual(values[3], zmm_msg.expected_serial)
        self.assertEqual(values[4], zmm_msg.actual_serial)

        # serialize the object to the channel -----------------------

        # XXX WRITE HEADER FIRST!

        # DEBUG
        print("DIR (ZMM_MSG): ", end=' ')
        print(dir(zmm_msg))
        # END
        zmm_msg.write_stand_alone(chan)
        chan.flip()

        # deserialize the channel, making a clone of the message ----
        (read_back, _) = MsgImpl.read(chan, self.str_obj_model)
        self.assertIsNotNone(read_back)

        # DEBUG
        print("position after mis-match read back is %d" % chan.position)
        # END

        # verify that the messages are identical --------------------
        self.assertTrue(zmm_msg.__eq__(read_back))

        # produce another message from the same values --------------
        zmm_msg2 = zone_mismatch_msg_cls(values)
        chan2 = Channel(BUFSIZE)
        zmm_msg2.write_stand_alone(chan2)
        chan2.flip()

        (copy2, _) = MsgImpl.read(chan2, self.str_obj_model)
        self.assertTrue(zmm_msg.__eq__(copy2))
        self.assertTrue(zmm_msg2.__eq__(copy2))  # GEEP
예제 #12
0
    def test_shutdown_msg(self):
        # DEBUG
        print("\nTEST_SHUTDOWN_MSG")
        # END

        # -----------------------------------------------------------
        # XXX This code has been crudely hacked from another test
        # module, and so needs careful review
        # -----------------------------------------------------------

        # verify that this adds 1 (msg) + 3 (field count) to the number
        # of entries in getters, writeStandAlones, etc

        msg_spec = self.str_obj_model.msgs[2]  # <------
        msg_name = msg_spec.name
        self.assertEqual('shutdown', msg_name)

        # Create a channel ------------------------------------------
        # its buffer will be used for both serializing # the instance
        # data and, by deserializing it, for creating a second instance.
        chan = Channel(BUFSIZE)
        buf = chan.buffer
        self.assertEqual(BUFSIZE, len(buf))

        # create the CorruptListMsg class ------------------------------
        shutdown_msg_cls = make_msg_class(self.str_obj_model, msg_name)

        # create a message instance ---------------------------------
        values = [
            RNG.next_file_name(8),
        ]  # list of quasi-random values
        sd_msg = shutdown_msg_cls(values)

        self.assertEqual(msg_name, sd_msg.name)
        # we don't have any nested enums or messages
        # pylint: disable=no-member
        self.assertEqual(0, len(sd_msg.enums))
        self.assertEqual(0, len(sd_msg.msgs))

        self.assertEqual(1, len(sd_msg.field_classes))  # <---
        self.assertEqual(1, len(sd_msg))  # number of fields in instance
        self.assertEqual(values[0], sd_msg.remarks)

        # serialize the object to the channel -----------------------
        sd_msg.write_stand_alone(chan)
        chan.flip()

        # deserialize the channel, making a clone of the message ----
        (read_back, _) = MsgImpl.read(chan, self.str_obj_model)
        self.assertIsNotNone(read_back)

        # DEBUG
        print("position after shutdown read back is %d" % chan.position)
        # END

        # verify that the messages are identical --------------------
        self.assertTrue(sd_msg.__eq__(read_back))

        # produce another message from the same values --------------
        sd_msg2 = shutdown_msg_cls(values)
        chan2 = Channel(BUFSIZE)
        sd_msg2.write_stand_alone(chan2)
        chan2.flip()

        (copy2, _) = MsgImpl.read(chan2, self.str_obj_model)
        self.assertTrue(sd_msg.__eq__(copy2))
        self.assertTrue(sd_msg2.__eq__(copy2))  # GEEP GEEP GEEP