# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # """ Console API for Qpid Management Framework """ import os import platform import qpid import struct import socket import re from qpid.peer import Closed from qpid.session import SessionDetached from qpid.connection import Connection, ConnectionFailed from qpid.datatypes import Message, RangedSet from qpid.util import connect, ssl, URL from qpid.codec010 import StringCodec as Codec from threading import Lock, Condition, Thread from time import time, strftime, gmtime from cStringIO import StringIO class Console: """ To access the asynchronous operations, a class must be derived from Console with overrides of any combination of the available methods. """ def brokerConnected(self, broker): """ Invoked when a connection is established to a broker """ pass def brokerDisconnected(self, broker): """ Invoked when the connection to a broker is lost """ pass def newPackage(self, name): """ Invoked when a QMF package is discovered. """ pass def newClass(self, kind, classKey): """ Invoked when a new class is discovered. Session.getSchema can be used to obtain details about the class.""" pass def newAgent(self, agent): """ Invoked when a QMF agent is discovered. """ pass def delAgent(self, agent): """ Invoked when a QMF agent disconects. """ pass def objectProps(self, broker, record): """ Invoked when an object is updated. """ pass def objectStats(self, broker, record): """ Invoked when an object is updated. """ pass def event(self, broker, event): """ Invoked when an event is raised. """ pass def heartbeat(self, agent, timestamp): """ Invoked when an agent heartbeat is received. """ pass def brokerInfo(self, broker): """ Invoked when the connection sequence reaches the point where broker information is available. """ pass def methodResponse(self, broker, seq, response): """ Invoked when a method response from an asynchronous method call is received. """ pass class BrokerURL(URL): def __init__(self, text): URL.__init__(self, text) socket.gethostbyname(self.host) if self.port is None: if self.scheme == URL.AMQPS: self.port = 5671 else: self.port = 5672 self.authName = str(self.user or "guest") self.authPass = str(self.password or "guest") self.authMech = "PLAIN" def name(self): return self.host + ":" + str(self.port) def match(self, host, port): return socket.gethostbyname(self.host) == socket.gethostbyname(host) and self.port == port class Session: """ An instance of the Session class represents a console session running against one or more QMF brokers. A single instance of Session is needed to interact with the management framework as a console. """ _CONTEXT_SYNC = 1 _CONTEXT_STARTUP = 2 _CONTEXT_MULTIGET = 3 DEFAULT_GET_WAIT_TIME = 60 def __init__(self, console=None, rcvObjects=True, rcvEvents=True, rcvHeartbeats=True, manageConnections=False, userBindings=False): """ Initialize a session. If the console argument is provided, the more advanced asynchronous features are available. If console is defaulted, the session will operate in a simpler, synchronous manner. The rcvObjects, rcvEvents, and rcvHeartbeats arguments are meaningful only if 'console' is provided. They control whether object updates, events, and agent-heartbeats are subscribed to. If the console is not interested in receiving one or more of the above, setting the argument to False will reduce tha bandwidth used by the API. If manageConnections is set to True, the Session object will manage connections to the brokers. This means that if a broker is unreachable, it will retry until a connection can be established. If a connection is lost, the Session will attempt to reconnect. If manageConnections is set to False, the user is responsible for handing failures. In this case, an unreachable broker will cause addBroker to raise an exception. If userBindings is set to False (the default) and rcvObjects is True, the console will receive data for all object classes. If userBindings is set to True, the user must select which classes the console shall receive by invoking the bindPackage or bindClass methods. This allows the console to be configured to receive only information that is relavant to a particular application. If rcvObjects id False, userBindings has no meaning. """ self.console = console self.brokers = [] self.packages = {} self.seqMgr = SequenceManager() self.cv = Condition() self.syncSequenceList = [] self.getResult = [] self.getSelect = [] self.error = None self.rcvObjects = rcvObjects self.rcvEvents = rcvEvents self.rcvHeartbeats = rcvHeartbeats self.userBindings = userBindings if self.console == None: self.rcvObjects = False self.rcvEvents = False self.rcvHeartbeats = False self.bindingKeyList = self._bindingKeys() self.manageConnections = manageConnections if self.userBindings and not self.rcvObjects: raise Exception("userBindings can't be set unless rcvObjects is set and a console is provided") def __repr__(self): return "QMF Console Session Manager (brokers: %d)" % len(self.brokers) def addBroker(self, target="localhost"): """ Connect to a Qpid broker. Returns an object of type Broker. """ url = BrokerURL(target) broker = Broker(self, url.host, url.port, url.authMech, url.authName, url.authPass, ssl = url.scheme == URL.AMQPS) self.brokers.append(broker) if not self.manageConnections: self.getObjects(broker=broker, _class="agent") return broker def delBroker(self, broker): """ Disconnect from a broker. The 'broker' argument is the object returned from the addBroker call """ if self.console: for agent in broker.getAgents(): self.console.delAgent(agent) broker._shutdown() self.brokers.remove(broker) del broker def getPackages(self): """ Get the list of known QMF packages """ for broker in self.brokers: broker._waitForStable() list = [] for package in self.packages: list.append(package) return list def getClasses(self, packageName): """ Get the list of known classes within a QMF package """ for broker in self.brokers: broker._waitForStable() list = [] if packageName in self.packages: for pkey in self.packages[packageName]: list.append(self.packages[packageName][pkey].getKey()) return list def getSchema(self, classKey): """ Get the schema for a QMF class """ for broker in self.brokers: broker._waitForStable() pname = classKey.getPackageName() pkey = classKey.getPackageKey() if pname in self.packages: if pkey in self.packages[pname]: return self.packages[pname][pkey] def bindPackage(self, packageName): """ Request object updates for all table classes within a package. """ if not self.userBindings or not self.rcvObjects: raise Exception("userBindings option not set for Session") key = "console.obj.*.*.%s.#" % packageName self.bindingKeyList.append(key) for broker in self.brokers: if broker.isConnected(): broker.amqpSession.exchange_bind(exchange="qpid.management", queue=broker.topicName, binding_key=key) def bindClass(self, pname, cname): """ Request object updates for a particular table class by package and class name. """ if not self.userBindings or not self.rcvObjects: raise Exception("userBindings option not set for Session") key = "console.obj.*.*.%s.%s.#" % (pname, cname) self.bindingKeyList.append(key) for broker in self.brokers: if broker.isConnected(): broker.amqpSession.exchange_bind(exchange="qpid.management", queue=broker.topicName, binding_key=key) def bindClassKey(self, classKey): """ Request object updates for a particular table class by class key. """ pname = classKey.getPackageName() cname = classKey.getClassName() self.bindClass(pname, cname) def getAgents(self, broker=None): """ Get a list of currently known agents """ brokerList = [] if broker == None: for b in self.brokers: brokerList.append(b) else: brokerList.append(broker) for b in brokerList: b._waitForStable() agentList = [] for b in brokerList: for a in b.getAgents(): agentList.append(a) return agentList def getObjects(self, **kwargs): """ Get a list of objects from QMF agents. All arguments are passed by name(keyword). The class for queried objects may be specified in one of the following ways: _schema = - supply a schema object returned from getSchema. _key = - supply a classKey from the list returned by getClasses. _class = - supply a class name as a string. If the class name exists in multiple packages, a _package argument may also be supplied. _objectId = - get the object referenced by the object-id If objects should be obtained from only one agent, use the following argument. Otherwise, the query will go to all agents. _agent = - supply an agent from the list returned by getAgents. If the get query is to be restricted to one broker (as opposed to all connected brokers), add the following argument: _broker = - supply a broker as returned by addBroker. The default timeout for this synchronous operation is 60 seconds. To change the timeout, use the following argument: _timeout =