Example #1
0
    def connect(self):
        with self.lock:
            if self.is_connected:
                return

            self._disconnecting = False
            conn_name = '%s(%s)' % (self.host, self.port)

            logger.info('Connecting to queue manager:`%s`, channel:`%s`'
                        ', connection info:`%s`' %
                        (self.queue_manager, self.channel, conn_name))
            self.mgr = self.mq.QueueManager(None)

            kwargs = {}
            cd = self.mq.cd()
            cd.ChannelName = self.channel
            cd.ConnectionName = conn_name.encode('utf8')
            cd.ChannelType = self.CMQC.MQCHT_CLNTCONN
            cd.TransportType = self.CMQC.MQXPT_TCP

            if self.ssl:
                if not (self.ssl_cipher_spec and self.ssl_key_repository):
                    msg = 'SSL support requires setting both ssl_cipher_spec and ssl_key_repository'
                    logger.error(msg)
                    raise BaseException(msg)

                kwargs['sco'] = self.mq.sco()
                kwargs['sco'].KeyRepository = self.ssl_key_repository
                cd.SSLCipherSpec = self.ssl_cipher_spec

            if self.use_shared_connections:
                connect_options = self.CMQC.MQCNO_HANDLE_SHARE_BLOCK
            else:
                connect_options = self.CMQC.MQCNO_HANDLE_SHARE_NONE

            try:
                self.mgr.connect_with_options(self.queue_manager,
                                              cd=cd,
                                              opts=connect_options,
                                              user=self.username,
                                              password=self.password,
                                              **kwargs)
            except self.mq.MQMIError as e:
                exc = WebSphereMQException(e, e.comp, e.reason)
                raise exc
            else:
                self.is_connected = True
                logger.info(
                    'Successfully connected to queue manager:`%s`, channel:`%s`, connection info:`%s`'
                    % (self.queue_manager, self.channel, conn_name))
Example #2
0
    def receive(self,
                destination,
                wait_interval,
                _connection_closing='zato.connection.closing'):
        if self._disconnecting:
            logger.info('Connection factory disconnecting, aborting receive')
            return _connection_closing
        else:
            if self.has_debug:
                logger.debug('receive -> not disconnecting')

        if not self.is_connected:
            if self.has_debug:
                logger.debug('receive -> _is_connected1 %s' %
                             self.is_connected)

            self.connect()

            if self.has_debug:
                logger.debug('receive -> _is_connected2 %s' %
                             self.is_connected)

        queue = self.get_queue_for_receiving(destination)

        try:
            # Default message descriptor ..
            md = self.mq.md()

            # .. and custom get message options
            gmo = self.mq.gmo()
            gmo.Options = self.CMQC.MQGMO_WAIT | self.CMQC.MQGMO_FAIL_IF_QUIESCING
            gmo.WaitInterval = wait_interval

            message = queue.get(None, md, gmo)

            return self._build_text_message(md, message)

        except self.mq.MQMIError, e:
            if e.reason == self.CMQC.MQRC_NO_MSG_AVAILABLE:
                text = 'No message available for destination:`%s`, wait_interval:`%s` ms' % (
                    destination, wait_interval)
                raise NoMessageAvailableException(text)
            else:
                logger.debug(
                    'Exception caught in get, comp:`%s`, reason:`%s`' %
                    (e.comp, e.reason))
                exc = WebSphereMQException(e, e.comp, e.reason)
                raise exc
Example #3
0
    def send(self, message, destination):
        if self._disconnecting:
            logger.info('Connection factory disconnecting, aborting receive')
            return
        else:
            if self.has_debug:
                logger.debug('send -> not disconnecting')

        if not self.is_connected:
            if self.has_debug:
                logger.debug('send -> _is_connected1 %s' % self.is_connected)

            self.connect()

            if self.has_debug:
                logger.debug('send -> _is_connected2 %s' % self.is_connected)

        destination = self._strip_prefixes_from_destination(destination)

        # Will consist of an MQRFH2 header and the actual business payload.
        buff = StringIO()

        # Build the message descriptor (MQMD)
        md = self._build_md(message)

        now = long(time() * 1000)

        # Create MQRFH2 header, if requested to
        if self.needs_jms:
            mqrfh2jms = MQRFH2JMS(self.needs_mcd, self.has_debug).build_header(
                message, destination, self.CMQC, now)
            buff.write(mqrfh2jms)

        if message.text is not None:
            buff.write(message.text.encode('utf-8'))

        body = buff.getvalue()
        buff.close()

        queue = self.get_queue_for_sending(destination)

        try:
            queue.put(body, md)
        except self.mq.MQMIError, e:
            logger.error('MQMIError in queue.put, comp:`%s`, reason:`%s`' %
                         (e.comp, e.reason))
            exc = WebSphereMQException(e, e.comp, e.reason)
            raise exc
Example #4
0
    def _build_text_message(self, md, message):
        if self.has_debug:
            logger.debug('Building a text message:`%r`, md:`%r`' % (repr(message), repr(md)))

        class_ = MQRFH2JMS if self.needs_jms else DummyMQRFH2JMS
        mqrfh2 = class_(self.needs_mcd)
        mqrfh2.build_folders_and_payload_from_message(message)

        jms_folder = mqrfh2.folders.get('jms', None)
        usr_folder = mqrfh2.folders.get('usr', None)

        # Create a message instance ..
        text_message = TextMessage()
        text_message.mqmd = md

        if usr_folder:
            for attr_name, attr_value in usr_folder.items():
                setattr(text_message, attr_name, str(attr_value))

        # .. set its JMS properties ..

        if jms_folder:
            if jms_folder.find('Dst') is not None:
                text_message.jms_destination = jms_folder.find('Dst').text.strip()

            if jms_folder.find('Exp') is not None:
                text_message.jms_expiration = long(jms_folder.find('Exp').text)
            else:
                text_message.jms_expiration = 0 # Same as in Java

            if jms_folder.find('Cid') is not None:
                text_message.jms_correlation_id = jms_folder.find('Cid').text

        else:
            text_message.jms_correlation_id = getattr(md, 'CorrelId', None)

        if md.Persistence == self.CMQC.MQPER_NOT_PERSISTENT:
            text_message.jms_delivery_mode = DELIVERY_MODE_NON_PERSISTENT
        elif md.Persistence in(self.CMQC.MQPER_PERSISTENT, self.CMQC.MQPER_PERSISTENCE_AS_Q_DEF):
            text_message.jms_delivery_mode = DELIVERY_MODE_PERSISTENT
        else:
            text = "Don't know how to handle md.Persistence mode:`%s`" % (md.Persistence)
            logger.error(text)
            exc = WebSphereMQException(text)
            raise exc

        if md.ReplyToQ.strip():
            if self.has_debug:
                logger.debug('Found md.ReplyToQ:`%r`' % md.ReplyToQ)
            text_message.jms_reply_to = 'queue://' + md.ReplyToQMgr.strip() + '/' + md.ReplyToQ.strip()

        text_message.jms_priority = md.Priority
        text_message.jms_message_id = md.MsgId
        text_message.put_date = md.PutDate.strip()
        text_message.put_time = md.PutTime.strip()
        text_message.jms_redelivered = bool(int(md.BackoutCount))

        text_message.JMSXUserID = md.UserIdentifier.strip()
        text_message.JMSXAppID = md.PutApplName.strip()
        text_message.JMSXDeliveryCount = md.BackoutCount
        text_message.JMSXGroupID = md.GroupId.strip()
        text_message.JMSXGroupSeq = md.MsgSeqNumber

        md_report_to_jms = {
            self.CMQC.MQRO_EXCEPTION: 'Exception',
            self.CMQC.MQRO_EXPIRATION: 'Expiration',
            self.CMQC.MQRO_COA: 'COA',
            self.CMQC.MQRO_COD: 'COD',
            self.CMQC.MQRO_PAN: 'PAN',
            self.CMQC.MQRO_NAN: 'NAN',
            self.CMQC.MQRO_PASS_MSG_ID: 'Pass_Msg_ID',
            self.CMQC.MQRO_PASS_CORREL_ID: 'Pass_Correl_ID',
            self.CMQC.MQRO_DISCARD_MSG: 'Discard_Msg',
        }

        for report_name, jms_header_name in iteritems(md_report_to_jms):
            report_value = md.Report & report_name
            if report_value:
                header_value = report_value
            else:
                header_value = None

            setattr(text_message, 'JMS_IBM_Report_' + jms_header_name, header_value)

        text_message.JMS_IBM_MsgType = md.MsgType
        text_message.JMS_IBM_Feedback = md.Feedback
        text_message.JMS_IBM_Format = md.Format.strip()
        text_message.JMS_IBM_PutApplType = md.PutApplType
        text_message.JMS_IBM_PutDate = md.PutDate.strip()
        text_message.JMS_IBM_PutTime = md.PutTime.strip()

        if md.MsgFlags & self.CMQC.MQMF_LAST_MSG_IN_GROUP:
            text_message.JMS_IBM_Last_Msg_In_Group = self.CMQC.MQMF_LAST_MSG_IN_GROUP
        else:
            text_message.JMS_IBM_Last_Msg_In_Group = None

        # .. and its payload too.
        if mqrfh2.payload:
            text_message.text = mqrfh2.payload.decode('utf-8', 'replace')

        return text_message
Example #5
0
    def send(self, message, destination):
        if self._disconnecting:
            logger.info('Connection factory disconnecting, aborting receive')
            return
        else:
            if self.has_debug:
                logger.debug('send -> not disconnecting')

        if not self.is_connected:
            if self.has_debug:
                logger.debug('send -> _is_connected1 %s' % self.is_connected)

            self.connect()

            if self.has_debug:
                logger.debug('send -> _is_connected2 %s' % self.is_connected)

        if not isinstance(destination, unicode):
            destination = destination.decode('utf8')

        destination = self._strip_prefixes_from_destination(destination)
        destination = destination.encode('utf8')

        # Will consist of an MQRFH2 header and the actual business payload.
        buff = BytesIO()

        # Build the message descriptor (MQMD)
        md = self._build_md(message)

        now = long(time() * 1000)

        # Create MQRFH2 header, if requested to
        if self.needs_jms:
            mqrfh2jms = MQRFH2JMS(self.needs_mcd, self.has_debug).build_header(message, destination, self.CMQC, now)
            buff.write(mqrfh2jms)

        if message.text is not None:
            buff.write(message.text.encode('utf8') if isinstance(message.text, unicode) else message.text)

        body = buff.getvalue()
        buff.close()

        queue = self.get_queue_for_sending(destination)

        #raise Exception('QQQ {}'.format(repr(md)))

        try:
            queue.put(body, md)
        except self.mq.MQMIError as e:
            logger.error('MQMIError in queue.put, comp:`%s`, reason:`%s`' % (e.comp, e.reason))
            exc = WebSphereMQException(e, e.comp, e.reason)
            raise exc

        if not self.cache_open_send_queues:
            queue.close()

        # Map the JMS headers overwritten by calling queue.put
        message.jms_message_id = md.MsgId
        message.jms_priority = md.Priority
        message.jms_correlation_id = md.CorrelId
        message.JMSXUserID = md.UserIdentifier
        message.JMSXAppID = md.PutApplName

        if md.PutDate and md.PutTime:
            message.jms_timestamp = self._get_jms_timestamp_from_md(md.PutDate.strip(), md.PutTime.strip())
            message.JMS_IBM_PutDate = md.PutDate.strip()
            message.JMS_IBM_PutTime = md.PutTime.strip()
        else:
            logger.warn('No md.PutDate and md.PutTime found, md:`%r`' % repr(md))

        # queue.put has succeeded, so overwrite expiration time as well
        if message.jms_expiration:
            message.jms_expiration += now

        if self.has_debug:
            logger.debug('Successfully sent a message `%s`, connection info `%s`' % (message, self.get_connection_info()))
            logger.debug('message:`%s`, body:`%r`, md:`%r`' % (message, body, repr(md)))