Beispiel #1
0
def execute(cmd, args, service_name, wait):
    """
        Execute an arbitrary command.

        \b
        Examples:
            python punch-q.py command execute -c /bin/ping -a "-c 1 192.168.0.1"
            python punch-q.py -C pq.yml command execute --cmd "/bin/ping" --args "-c 5 192.168.0.8" --wait 8
    """

    # Generate a service name if none was provided
    if not service_name:
        service_name = uuid.uuid4()

    # Cleanup the service name to remove spaces and dashes and limit to 16 chars
    service_name = str(service_name).replace('-', '').replace(' ', '')[0:16]

    # information
    click.secho('Cmd: {0}'.format(cmd), bold=True)
    click.secho('Arg: {0}'.format(args), bold=True)
    click.secho('Service Name: {0}\n'.format(service_name))

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    # create the service
    click.secho('Creating service...', dim=True)
    args = {
        pymqi.CMQC.MQCA_SERVICE_NAME: service_name,
        pymqi.CMQC.MQIA_SERVICE_CONTROL: pymqi.CMQC.MQSVC_CONTROL_MANUAL,
        pymqi.CMQC.MQIA_SERVICE_TYPE: pymqi.CMQC.MQSVC_TYPE_COMMAND,
        pymqi.CMQC.MQCA_SERVICE_START_COMMAND: str(cmd),
        pymqi.CMQC.MQCA_SERVICE_START_ARGS: str(args)
    }
    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_CREATE_SERVICE(args)

    # start the service
    click.secho('Starting service...', fg='green')
    args = {pymqi.CMQC.MQCA_SERVICE_NAME: service_name}

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_START_SERVICE(args)

    click.secho('Giving the service {0} second(s) to live...'.format(wait),
                dim=True)
    time.sleep(wait)

    # delete service
    click.secho('Cleaning up service...', dim=True)
    args = {pymqi.CMQC.MQCA_SERVICE_NAME: service_name}

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_DELETE_SERVICE(args)

    qmgr.disconnect()

    click.secho('Done', fg='green')
Beispiel #2
0
    def get_metrics_channels(self):
        with self.query_qmgr() as conn:
            args = {
                CMQCFC.MQCACH_CHANNEL_NAME: '*',
            }

            channel_metrics = {
                'CMQCFC.MQCMD_INQUIRE_CHANNEL_STATUS': {
                    CMQCFC.MQIACH_CHANNEL_STATUS: {
                        'key': 'channelStatus'
                    },
                    CMQCFC.MQIACH_MSGS: {
                        'key': 'channelMessages'
                    },
                    CMQCFC.MQIACH_BYTES_SENT: {
                        'key': 'channelBytesSent'
                    },
                    CMQCFC.MQIACH_BYTES_RECEIVED: {
                        'key': 'channelBytesReceived'
                    },
                    CMQCFC.MQIACH_BUFFERS_SENT: {
                        'key': 'channelBuffersSent'
                    },
                    CMQCFC.MQIACH_BUFFERS_RECEIVED: {
                        'key': 'channelBuffersReceived'
                    },
                    CMQCFC.MQCACH_LAST_MSG_DATE: {
                        'key': 'channelLastMsgDate'
                    },
                    CMQCFC.MQCACH_LAST_MSG_TIME: {
                        'key': 'channelLastMsgTime'
                    },
                    CMQCFC.MQIACH_CURRENT_SHARING_CONVS: {
                        'key': 'channelCurrentSharingConvs'
                    },
                },
            }

            local_metrics = []

            for command in channel_metrics:

                for channel in getattr(pymqi.PCFExecute(conn), command)(args):
                    channel_name = channel[CMQCFC.MQCACH_CHANNEL_NAME].strip()

                    for attribute, properties in channel_metrics[
                            command].items():
                        if attribute in channel.keys():

                            local_metrics.append({
                                'key': properties["key"],
                                'value': channel[attribute],
                                'dimensions': {
                                    'Channel': channel_name
                                },
                                'type': 'absolute'
                            })

            with self.lock:
                self.metrics_to_report.extend(local_metrics)
Beispiel #3
0
 def delete_queue(self, sub_desc, queue_name):
     # must be unmanaged
     if not sub_desc["Options"] & pymqi.CMQC.MQSO_MANAGED:
         pcf = pymqi.PCFExecute(self.qmgr)
         args = {pymqi.CMQC.MQCA_Q_NAME: utils.py3str2bytes(queue_name),
                 pymqi.CMQCFC.MQIACF_PURGE: pymqi.CMQCFC.MQPO_YES}
         pcf.MQCMD_DELETE_Q(args)
Beispiel #4
0
    def get_metrics_queue_managers(self):
        with self.query_qmgr() as conn:

            queue_manager_metrics = {
                'CMQCFC.MQCMD_INQUIRE_Q_MGR_STATUS': {
                    CMQCFC.MQIACF_Q_MGR_STATUS: {
                        'key': 'queueManagerStatus'
                    },
                    CMQCFC.MQIACF_CONNECTION_COUNT: {
                        'key': 'queueManagerConnections'
                    },
                },
            }

            local_metrics = []

            for command in queue_manager_metrics:
                for queue_manager in getattr(pymqi.PCFExecute(conn),
                                             command)():
                    for attribute, properties in queue_manager_metrics[
                            command].items():
                        if attribute in queue_manager.keys():

                            local_metrics.append({
                                'key':
                                properties["key"],
                                'value':
                                queue_manager[attribute],
                                'type':
                                'absolute'
                            })

            with self.lock:
                self.metrics_to_report.extend(local_metrics)
    def _submit_channel_status(self, queue_manager, search_channel_name, tags,
                               config):
        """Submit channel status
        :param search_channel_name might contain wildcard characters
        """
        search_channel_tags = tags + ["channel:{}".format(search_channel_name)]
        try:
            args = {
                pymqi.CMQCFC.MQCACH_CHANNEL_NAME:
                ensure_bytes(search_channel_name)
            }
            pcf = pymqi.PCFExecute(queue_manager)
            response = pcf.MQCMD_INQUIRE_CHANNEL_STATUS(args)
            self.service_check(self.CHANNEL_SERVICE_CHECK, AgentCheck.OK,
                               search_channel_tags)
        except pymqi.MQMIError as e:
            self.log.warning("Error getting CHANNEL stats {}".format(e))
            self.service_check(self.CHANNEL_SERVICE_CHECK, AgentCheck.CRITICAL,
                               search_channel_tags)
        else:
            for channel_info in response:
                channel_name = ensure_unicode(
                    channel_info[pymqi.CMQCFC.MQCACH_CHANNEL_NAME]).strip()
                channel_tags = tags + ["channel:{}".format(channel_name)]

                channel_status = channel_info[
                    pymqi.CMQCFC.MQIACH_CHANNEL_STATUS]

                self._submit_channel_count(channel_name, channel_status,
                                           channel_tags)
                self._submit_status_check(channel_name, channel_status,
                                          channel_tags, config)
Beispiel #6
0
    def setUpClass(cls):
        """Initialize test environment."""
        cls.prefix = os.environ.get('PYMQI_TEST_OBJECT_PREFIX', 'PYMQI.')

        # max length of queue names is 48 characters
        cls.queue_name = '{prefix}MSG.QUEUE'.format(prefix=config.MQ.QUEUE.PREFIX)
        cls.queue_manager = config.MQ.QM.NAME
        cls.channel = config.MQ.QM.CHANNEL
        cls.host = config.MQ.QM.HOST
        cls.port = config.MQ.QM.PORT
        cls.user = config.MQ.QM.USER
        cls.password = config.MQ.QM.PASSWORD

        cls.conn_info = '{0}({1})'.format(cls.host, cls.port)

        if pymqi.__mqbuild__ == 'server':
            cls.qmgr = pymqi.QueueManager(cls.queue_manager)
        else:
            cls.qmgr = pymqi.QueueManager(None)
            cls.qmgr.connectTCPClient(cls.queue_manager, pymqi.CD(), cls.channel,
                                      cls.conn_info, cls.user, cls.password)

        cls.pcf = pymqi.PCFExecute(cls.qmgr, response_wait_interval=15000)

        cls.version = cls.inquire_qmgr_version().decode()
Beispiel #7
0
    def get_pcf_channel_metrics(self, queue_manager, tags, config):
        args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: ensure_bytes('*')}

        try:
            pcf = pymqi.PCFExecute(queue_manager)
            response = pcf.MQCMD_INQUIRE_CHANNEL(args)
        except pymqi.MQMIError as e:
            self.log.warning("Error getting CHANNEL stats %s", e)
        else:
            channels = len(response)
            mname = '{}.channel.channels'.format(self.METRIC_PREFIX)
            self.gauge(mname, channels, tags=tags)

            for channel_info in response:
                channel_name = ensure_unicode(channel_info[pymqi.CMQCFC.MQCACH_CHANNEL_NAME]).strip()
                channel_tags = tags + ["channel:{}".format(channel_name)]

                self._submit_metrics_from_properties(channel_info, metrics.channel_metrics(), channel_tags)

        # Check specific channels
        # If a channel is not discoverable, a user may want to check it specifically.
        # Specific channels are checked first to send channel metrics and `ibm_mq.channel` service checks
        # at the same time, but the end result is the same in any order.
        for channel in config.channels:
            self._submit_channel_status(queue_manager, channel, tags, config)

        # Grab all the discoverable channels
        self._submit_channel_status(queue_manager, '*', tags, config, config.channels)
Beispiel #8
0
    def get_pcf_queue_status_metrics(self, queue_manager, queue_name, tags):
        try:
            args = {
                pymqi.CMQC.MQCA_Q_NAME: pymqi.ensure_bytes(queue_name),
                pymqi.CMQC.MQIA_Q_TYPE: pymqi.CMQC.MQQT_ALL,
                pymqi.CMQCFC.MQIACF_Q_STATUS_ATTRS: pymqi.CMQCFC.MQIACF_ALL,
            }
            pcf = pymqi.PCFExecute(queue_manager, convert=self.config.convert_endianness)
            response = pcf.MQCMD_INQUIRE_Q_STATUS(args)
        except pymqi.MQMIError as e:
            # Don't warn if no messages, see:
            # https://github.com/dsuch/pymqi/blob/v1.12.0/docs/examples.rst#how-to-wait-for-multiple-messages
            if not (e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE):
                self.warning("Error getting pcf queue stats for %s: %s", queue_name, e)
        else:
            # Response is a list. It likely has only one member in it.
            for queue_info in response:
                for mname, values in iteritems(metrics.pcf_metrics()):
                    failure_value = values['failure']
                    pymqi_value = values['pymqi_value']
                    mname = '{}.queue.{}'.format(metrics.METRIC_PREFIX, mname)
                    m = int(queue_info[pymqi_value])

                    if m > failure_value:
                        self.send_metric(GAUGE, mname, m, tags=tags)
                    else:
                        msg = "Unable to get {}, turn on queue level monitoring to access these metrics for {}"
                        msg = msg.format(mname, queue_name)
                        self.log.debug(msg)
Beispiel #9
0
 def delete_queue(self, queue_name):
     pcf = pymqi.PCFExecute(self.qmgr)
     args = {
         pymqi.CMQC.MQCA_Q_NAME: utils.py3str2bytes(queue_name),
         pymqi.CMQCFC.MQIACF_PURGE: pymqi.CMQCFC.MQPO_YES
     }
     pcf.MQCMD_DELETE_Q(args)
Beispiel #10
0
def create_process(qmgr, file_loc):
    # create process to initiate aut script
    app_type = CMQC.MQAT_UNIX
    proc_desc = 'Process to run AUT files'
    app_id = file_loc
    env_data = '&'

    pargs = {
        CMQC.MQCA_PROCESS_NAME: proc_name,
        CMQC.MQCA_PROCESS_DESC: proc_desc,
        CMQC.MQIA_APPL_TYPE: app_type,
        CMQC.MQCA_APPL_ID: app_id,
        CMQC.MQCA_ENV_DATA: env_data
    }
    try:
        pcf = pymqi.PCFExecute(qmgr)
        print '! - trying to create process'
        pcf.MQCMD_CREATE_PROCESS(pargs)
        print '  - process was created'
    except pymqi.MQMIError, e:
        # need to check for other exceptions as well like queue manager not reachable
        if e.comp == CMQC.MQCC_FAILED and e.reason == CMQCFC.MQRCCF_OBJECT_ALREADY_EXISTS:
            print ' * process already exists'
            print '  - updating process'
            try:
                print '  ! - trying to update'
                pcf.MQCMD_CHANGE_PROCESS(pargs)
                print '    - updated'
            except pymqi.MQMIError, f:
                print '  * did not update process'
                print '  - completion code: ', f.comp
                print '  - reason code:', f.reason
            pass
Beispiel #11
0
    def setUpClass(cls):
        """Initialize test environment."""
        super(TestPCF, cls).setUpClass()

        # max length of queue names is 48 characters
        cls.queue_name = "{prefix}PCF.QUEUE".format(prefix=cls.prefix)
        cls.pcf = pymqi.PCFExecute(cls.qmgr, response_wait_interval=600)
Beispiel #12
0
 def delete_sub(self, sub_desc):
     # can only delete a durable subscription
     if sub_desc["Options"] & pymqi.CMQC.MQSO_DURABLE:
         subname = sub_desc.get_vs("SubName")
         pcf = pymqi.PCFExecute(self.qmgr)
         args = {pymqi.CMQCFC.MQCACF_SUB_NAME: subname}
         pcf.MQCMD_DELETE_SUBSCRIPTION(args)
Beispiel #13
0
 def queue_stats(self, queue_manager, queue_name, tags):
     """
     Grab stats from queues
     """
     pcf = None
     try:
         args = {pymqi.CMQC.MQCA_Q_NAME: pymqi.ensure_bytes(queue_name), pymqi.CMQC.MQIA_Q_TYPE: pymqi.CMQC.MQQT_ALL}
         pcf = pymqi.PCFExecute(
             queue_manager, response_wait_interval=self.config.timeout, convert=self.config.convert_endianness
         )
         response = pcf.MQCMD_INQUIRE_Q(args)
     except pymqi.MQMIError as e:
         # Don't warn if no messages, see:
         # https://github.com/dsuch/pymqi/blob/v1.12.0/docs/examples.rst#how-to-wait-for-multiple-messages
         if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE:
             self.log.debug("No stat messages available for queue %s", queue_name)
         else:
             self.warning("Error getting queue stats for %s: %s", queue_name, e)
     else:
         # Response is a list. It likely has only one member in it.
         for queue_info in response:
             self._submit_queue_stats(queue_info, queue_name, tags)
     finally:
         if pcf is not None:
             pcf.disconnect()
Beispiel #14
0
    def get_pcf_queue_status_metrics(self, queue_manager, queue_name, tags):
        try:
            args = {
                pymqi.CMQC.MQCA_Q_NAME: ensure_bytes(queue_name),
                pymqi.CMQC.MQIA_Q_TYPE: pymqi.CMQC.MQQT_ALL,
                pymqi.CMQCFC.MQIACF_Q_STATUS_ATTRS: pymqi.CMQCFC.MQIACF_ALL,
            }
            pcf = pymqi.PCFExecute(queue_manager)
            response = pcf.MQCMD_INQUIRE_Q_STATUS(args)
        except pymqi.MQMIError as e:
            self.warning("Error getting pcf queue stats for %s: %s", queue_name, e)
        else:
            # Response is a list. It likely has only one member in it.
            for queue_info in response:
                for mname, values in iteritems(metrics.pcf_metrics()):
                    failure_value = values['failure']
                    pymqi_value = values['pymqi_value']
                    mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)
                    m = int(queue_info[pymqi_value])

                    if m > failure_value:
                        self.gauge(mname, m, tags=tags)
                    else:
                        msg = "Unable to get {}, turn on queue level monitoring to access these metrics for {}"
                        msg = msg.format(mname, queue_name)
                        log.debug(msg)
Beispiel #15
0
    def _submit_channel_status(self, queue_manager, search_channel_name, tags, config, channels_to_skip=None):
        """Submit channel status

        Note: Error 3065 (MQRCCF_CHL_STATUS_NOT_FOUND) might indicate that the channel has not been used.
        More info: https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.1.0/com.ibm.mq.doc/fm16690_.htm

        :param search_channel_name might contain wildcard characters
        """
        channels_to_skip = channels_to_skip or []
        search_channel_tags = tags + ["channel:{}".format(search_channel_name)]
        try:
            args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: ensure_bytes(search_channel_name)}
            pcf = pymqi.PCFExecute(queue_manager)
            response = pcf.MQCMD_INQUIRE_CHANNEL_STATUS(args)
            self.service_check(self.CHANNEL_SERVICE_CHECK, AgentCheck.OK, search_channel_tags)
        except pymqi.MQMIError as e:
            self.service_check(self.CHANNEL_SERVICE_CHECK, AgentCheck.CRITICAL, search_channel_tags)
            if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQCFC.MQRCCF_CHL_STATUS_NOT_FOUND:
                self.log.debug("Channel status not found for channel %s: %s", search_channel_name, e)
            else:
                self.log.warning("Error getting CHANNEL status for channel %s: %s", search_channel_name, e)
        else:
            for channel_info in response:
                channel_name = ensure_unicode(channel_info[pymqi.CMQCFC.MQCACH_CHANNEL_NAME]).strip()
                if channel_name in channels_to_skip:
                    continue
                channel_tags = tags + ["channel:{}".format(channel_name)]

                self._submit_metrics_from_properties(channel_info, metrics.channel_status_metrics(), channel_tags)

                channel_status = channel_info[pymqi.CMQCFC.MQIACH_CHANNEL_STATUS]
                self._submit_channel_count(channel_name, channel_status, channel_tags)
                self._submit_status_check(channel_name, channel_status, channel_tags, config)
Beispiel #16
0
 def test_mq_level(self):
     """ We should be connecting to an MQ 8.0+ queue manager.
     """
     conn = self.get_conn()
     pcf = pymqi.PCFExecute(conn)
     command_level = pcf.MQCMD_INQUIRE_Q_MGR()[0][CMQC.MQIA_COMMAND_LEVEL]
     self.assertGreaterEqual(command_level, 800)
     conn.disconnect()
Beispiel #17
0
 def create_admin_subscription(self, destination_class, subname, queue_name, topic_string):
     pcf = pymqi.PCFExecute(self.qmgr)
     args = {pymqi.CMQCFC.MQCACF_SUB_NAME: utils.py3str2bytes(subname),
             pymqi.CMQC.MQCA_TOPIC_STRING: utils.py3str2bytes(topic_string),
             pymqi.CMQCFC.MQIACF_DESTINATION_CLASS: destination_class}
     if destination_class is pymqi.CMQC.MQDC_PROVIDED:
         args[pymqi.CMQCFC.MQCACF_DESTINATION] = utils.py3str2bytes(queue_name)
     pcf.MQCMD_CREATE_SUBSCRIPTION(args)
Beispiel #18
0
 def delete_channel(self, channel_name):
     """Delete channel."""
     pcf = pymqi.PCFExecute(self.qmgr)
     attrs = []
     attrs.append(
         pymqi.CFST(Parameter=pymqi.CMQCFC.MQCACH_CHANNEL_NAME,
                    String=utils.py3str2bytes(channel_name)))
     pcf.MQCMD_DELETE_CHANNEL(attrs)
Beispiel #19
0
def channels(prefix):
    """
        Show channels.
    """

    mqstate.validate(['host', 'port', 'channel'])

    args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: str(prefix)}
    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)
    pcf = pymqi.PCFExecute(qmgr)

    try:

        click.secho(
            'Showing channels with prefix: \'{0}\'...\n'.format(prefix),
            dim=True)
        response = pcf.MQCMD_INQUIRE_CHANNEL(args)

    except pymqi.MQMIError as sce:

        if sce.comp == pymqi.CMQC.MQCC_FAILED and sce.reason == pymqi.CMQC.MQRC_UNKNOWN_OBJECT_NAME:
            click.secho('No channels matched prefix [%s]'.format(prefix),
                        fg='red')

        else:
            raise sce

    else:

        t = get_table_handle([
            'Name',
            'Type',
            'MCA UID',
            'Conn Name',
            'Xmit Queue',
            'Description',
            'SSL Cipher',
        ])

        for channel_info in response:
            t.append_row([
                channel_info.get(pymqi.CMQCFC.MQCACH_CHANNEL_NAME, '').strip(),
                channel_type_to_name(
                    channel_info.get(pymqi.CMQCFC.MQIACH_CHANNEL_TYPE)),
                channel_info.get(pymqi.CMQCFC.MQCACH_MCA_USER_ID, ''),
                channel_info.get(pymqi.CMQCFC.MQCACH_CONNECTION_NAME,
                                 '').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_XMIT_Q_NAME, '').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_DESC, '').strip(),
                # channel_info.get(pymqi.CMQCFC.MQCACH_PASSWORD, '(unknown)').strip(),
                channel_info.get(pymqi.CMQCFC.MQCACH_SSL_CIPHER_SPEC,
                                 '').strip(),
                # channel_info.get(pymqi.CMQCFC.MQCACH_SSL_PEER_NAME, '').strip(),
            ])
        click.secho(t.get_string())

    qmgr.disconnect()
Beispiel #20
0
def ping():
    """
        Ping a queue manager.
    """

    mqstate.validate(['host', 'port'])

    qmgr = pymqi.connect(mqstate.qm_name, mqstate.channel, mqstate.get_host(),
                         mqstate.username, mqstate.password)

    pcf = pymqi.PCFExecute(qmgr)
    pcf.MQCMD_PING_Q_MGR()
    click.secho('Queue manager command server is responsive.', fg='green')

    # Attempt to determine the MQ command level.
    mq_params = pcf.MQCMD_INQUIRE_Q_MGR(
        {pymqi.CMQCFC.MQCMD_INQUIRE_SYSTEM: '*'})

    # Get the queue manager status
    mq_status = pcf.MQCMD_INQUIRE_Q_MGR_STATUS()[0]

    # A number of these are not in CMQC, so this comment is a reference:
    # MQCA_INSTALLATION_DESC: 2115
    # MQCA_INSTALLATION_NAME: 2116
    # MQCA_INSTALLATION_PATH: 2117
    # MQCACF_LOG_PATH: 3074
    # MQCACF_Q_MGR_START_DATE: 3175
    # MQCACF_Q_MGR_START_TIME: 3176

    click.secho('Queue Manager Status:', bold=True)
    click.secho('---------------------', bold=True)
    click.secho('Command Level:             {0}'.format(
        mq_params[0][pymqi.CMQC.MQIA_COMMAND_LEVEL]),
                bold=True)
    click.secho('Queue Manager Name:        {0}'.format(
        mq_status.get(pymqi.CMQC.MQCA_Q_MGR_NAME, '(unknown)')),
                bold=True)
    click.secho('Installation Name:         {0}'.format(
        mq_status.get(2116, '(unknown)')),
                bold=True)
    click.secho('Installation Path:         {0}'.format(
        mq_status.get(2117, '(unknown)')),
                bold=True)
    click.secho('Installation Description:  {0}'.format(
        mq_status.get(2115, '(unknown)')),
                bold=True)
    click.secho('Log Path:                  {0}'.format(
        mq_status.get(3074, '(unknown)')),
                bold=True)
    click.secho('Queue Manager Start Time:  {0}'.format(' '.join(
        [mq_status.get(3175, '').strip(),
         mq_status.get(3176, '').strip()])),
                bold=True)
    click.secho('\n')

    click.secho('Successfully queried queue manager status.', fg='green')

    qmgr.disconnect()
Beispiel #21
0
    def create_queue(self, queue_name):
        queue_type = pymqi.CMQC.MQQT_LOCAL
        max_depth = 123456

        args = {pymqi.CMQC.MQCA_Q_NAME: utils.py3str2bytes(queue_name),
                pymqi.CMQC.MQIA_Q_TYPE: queue_type,
                pymqi.CMQC.MQIA_MAX_Q_DEPTH: max_depth}
        pcf = pymqi.PCFExecute(self.qmgr)
        pcf.MQCMD_CREATE_Q(args)
Beispiel #22
0
 def create_channel(self, channel_name, args=None):
     if args:
         args[pymqi.CMQCFC.MQCACH_CHANNEL_NAME] = utils.py3str2bytes(channel_name)
     else:
         args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: utils.py3str2bytes(channel_name),
                 pymqi.CMQCFC.MQIACH_CHANNEL_TYPE: pymqi.CMQC.MQCHT_SVRCONN,
                 pymqi.CMQCFC.MQIACF_REPLACE: pymqi.CMQCFC.MQRP_YES}
     pcf = pymqi.PCFExecute(self.qmgr)
     pcf.MQCMD_CREATE_CHANNEL(args)
Beispiel #23
0
 def create_queue(self, queue_name, max_depth=5000, args=None):
     if args:
         args[pymqi.CMQC.MQCA_Q_NAME] = utils.py3str2bytes(queue_name)
     else:
         args = {pymqi.CMQC.MQCA_Q_NAME: utils.py3str2bytes(queue_name),
                 pymqi.CMQC.MQIA_Q_TYPE: pymqi.CMQC.MQQT_LOCAL,
                 pymqi.CMQC.MQIA_MAX_Q_DEPTH: max_depth,
                 pymqi.CMQCFC.MQIACF_REPLACE: pymqi.CMQCFC.MQRP_YES}
     pcf = pymqi.PCFExecute(self.qmgr)
     pcf.MQCMD_CREATE_Q(args)
Beispiel #24
0
 def query_qmgr():
     global qmgr, pcf
     queue_manager = "QM01"
     channel = "CHANNEL.1"
     host = "127.0.0.1"
     port = "1434"
     conn_info = "%s(%s)" % (host, port)
     qmgr = pymqi.connect(queue_manager, channel, conn_info)
     pcf = pymqi.PCFExecute(qmgr)
     query_func()
     qmgr.disconnect()
Beispiel #25
0
 def delete_queue(self, queue_name):
     """Delete queue."""
     pcf = pymqi.PCFExecute(self.qmgr)
     attrs = []
     attrs.append(
         pymqi.CFST(Parameter=pymqi.CMQC.MQCA_Q_NAME,
                    String=utils.py3str2bytes(queue_name)))
     attrs.append(
         pymqi.CFIN(Parameter=pymqi.CMQCFC.MQIACF_PURGE,
                    Value=pymqi.CMQCFC.MQPO_YES))
     pcf.MQCMD_DELETE_Q(attrs)
Beispiel #26
0
    def create_queue(self, queue_name):
        queue_type = pymqi.CMQC.MQQT_LOCAL
        max_depth = 5000

        args = {pymqi.CMQC.MQCA_Q_NAME: utils.py3str2bytes(queue_name),
                pymqi.CMQC.MQIA_Q_TYPE: queue_type,
                pymqi.CMQC.MQIA_MAX_Q_DEPTH: max_depth, 
                pymqi.CMQCFC.MQIACF_REPLACE: pymqi.CMQCFC.MQRP_YES}
        pcf = pymqi.PCFExecute(self.qmgr)
        pcf.MQCMD_CREATE_Q(args)
        pcf.disconnect
    def _submit_channel_status(self, queue_manager, search_channel_name, tags, channels_to_skip=None):
        """Submit channel status

        Note: Error 3065 (MQRCCF_CHL_STATUS_NOT_FOUND) might indicate that the channel has not been used.
        More info: https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.1.0/com.ibm.mq.doc/fm16690_.htm

        :param search_channel_name might contain wildcard characters
        """
        channels_to_skip = channels_to_skip or []
        search_channel_tags = tags + ["channel:{}".format(search_channel_name)]
        pcf = None
        try:
            args = {pymqi.CMQCFC.MQCACH_CHANNEL_NAME: pymqi.ensure_bytes(search_channel_name)}
            pcf = pymqi.PCFExecute(
                queue_manager, response_wait_interval=self.config.timeout, convert=self.config.convert_endianness
            )
            response = pcf.MQCMD_INQUIRE_CHANNEL_STATUS(args)
            self.service_check(
                self.CHANNEL_SERVICE_CHECK, AgentCheck.OK, search_channel_tags, hostname=self.config.hostname
            )
        except pymqi.MQMIError as e:
            if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQCFC.MQRCCF_CHL_STATUS_NOT_FOUND:
                self.service_check(
                    self.CHANNEL_SERVICE_CHECK, AgentCheck.CRITICAL, search_channel_tags, hostname=self.config.hostname
                )
                self.log.debug("Channel status not found for channel %s: %s", search_channel_name, e)
            elif e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE:
                self.service_check(
                    self.CHANNEL_SERVICE_CHECK, AgentCheck.UNKNOWN, search_channel_tags, hostname=self.config.hostname
                )
                self.log.debug("There are no messages available for channel %s", search_channel_name)
            else:
                self.service_check(
                    self.CHANNEL_SERVICE_CHECK, AgentCheck.CRITICAL, search_channel_tags, hostname=self.config.hostname
                )
                self.log.warning("Error getting CHANNEL status for channel %s: %s", search_channel_name, e)
        else:
            for channel_info in response:
                channel_name = to_string(channel_info[pymqi.CMQCFC.MQCACH_CHANNEL_NAME]).strip()
                if channel_name in channels_to_skip:
                    continue
                channel_tags = tags + ["channel:{}".format(channel_name)]

                self._submit_metrics_from_properties(
                    channel_info, channel_name, metrics.channel_status_metrics(), channel_tags
                )

                channel_status = channel_info[pymqi.CMQCFC.MQIACH_CHANNEL_STATUS]
                self._submit_channel_count(channel_name, channel_status, channel_tags)
                self._submit_status_check(channel_name, channel_status, channel_tags)
        finally:
            if pcf is not None:
                pcf.disconnect()
Beispiel #28
0
    def get_pcf_queue_status_metrics(self, queue_manager, queue_name, tags):
        pcf = None
        try:
            args = {
                pymqi.CMQC.MQCA_Q_NAME: pymqi.ensure_bytes(queue_name),
                pymqi.CMQC.MQIA_Q_TYPE: pymqi.CMQC.MQQT_ALL,
                pymqi.CMQCFC.MQIACF_Q_STATUS_ATTRS: pymqi.CMQCFC.MQIACF_ALL,
            }
            pcf = pymqi.PCFExecute(
                queue_manager, response_wait_interval=self.config.timeout, convert=self.config.convert_endianness
            )
            response = pcf.MQCMD_INQUIRE_Q_STATUS(args)
        except pymqi.MQMIError as e:
            # Don't warn if no messages, see:
            # https://github.com/dsuch/pymqi/blob/v1.12.0/docs/examples.rst#how-to-wait-for-multiple-messages
            if e.comp == pymqi.CMQC.MQCC_FAILED and e.reason == pymqi.CMQC.MQRC_NO_MSG_AVAILABLE:
                self.log.debug("No PCF queue status messages available for queue %s", queue_name)
            else:
                self.warning("Error getting pcf queue status for %s: %s", queue_name, e)
        else:
            # Response is a list. It likely has only one member in it.
            for queue_info in response:
                for mname, values in iteritems(metrics.pcf_metrics()):
                    metric_name = '{}.queue.{}'.format(metrics.METRIC_PREFIX, mname)
                    try:
                        if callable(values):
                            metric_value = values(self.config.qm_timezone, queue_info)
                            if metric_value is not None:
                                self.send_metric(GAUGE, metric_name, metric_value, tags=tags)
                            else:
                                msg = """
                                    Unable to get %s. Turn on queue level monitoring to access these metrics for %s.
                                    Check `DISPLAY QSTATUS(%s) MONITOR`.
                                    """
                                self.log.debug(msg, metric_name, queue_name, queue_name)
                        else:
                            failure_value = values['failure']
                            pymqi_value = values['pymqi_value']
                            metric_value = int(queue_info.get(pymqi_value, None))

                            if metric_value > failure_value:
                                self.send_metric(GAUGE, metric_name, metric_value, tags=tags)
                            else:
                                msg = "Unable to get {}, turn on queue level monitoring to access these metrics for {}"
                                msg = msg.format(metric_name, queue_name)
                                self.log.debug(msg)
                    except Exception as e:
                        msg = "Unable to get metric {} from queue {}. Error is {}.".format(metric_name, queue_name, e)
                        self.log.warning(msg)
        finally:
            if pcf is not None:
                pcf.disconnect()
Beispiel #29
0
 def get_pcf_queue_reset_metrics(self, queue_manager, queue_name, tags):
     try:
         args = {pymqi.CMQC.MQCA_Q_NAME: pymqi.ensure_bytes(queue_name)}
         pcf = pymqi.PCFExecute(queue_manager, convert=self.config.convert_endianness)
         response = pcf.MQCMD_RESET_Q_STATS(args)
     except pymqi.MQMIError as e:
         self.warning("Error getting pcf queue stats for %s: %s", queue_name, e)
     else:
         # Response is a list. It likely has only one member in it.
         for queue_info in response:
             metrics_map = metrics.pcf_status_reset_metrics()
             prefix = "{}.queue".format(metrics.METRIC_PREFIX)
             self.send_metrics_from_properties(queue_info, metrics_map, prefix, tags)
Beispiel #30
0
 def get_pcf_queue_reset_metrics(self, queue_manager, queue_name, tags):
     try:
         args = {pymqi.CMQC.MQCA_Q_NAME: ensure_bytes(queue_name)}
         pcf = pymqi.PCFExecute(queue_manager)
         response = pcf.MQCMD_RESET_Q_STATS(args)
     except pymqi.MQMIError as e:
         self.warning("Error getting pcf queue stats for %s: %s", queue_name, e)
     else:
         # Response is a list. It likely has only one member in it.
         for queue_info in response:
             for metric_name, (pymqi_type, metric_type) in iteritems(metrics.pcf_status_reset_metrics()):
                 metric_full_name = '{}.queue.{}'.format(self.METRIC_PREFIX, metric_name)
                 metric_value = int(queue_info[pymqi_type])
                 self._send_metric(metric_type, metric_full_name, metric_value, tags)