summaryrefslogtreecommitdiff
path: root/qpid/tools/src/py/qpidtoollibs/broker.py
blob: 98c1bfaa328bbffcb7e8f74eec5eda74c4c84a6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#
# 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.
#

from qpid.messaging import Message
try:
  from uuid import uuid4
except ImportError:
  from qpid.datatypes import uuid4

class BrokerAgent(object):
  """
  Proxy for a manageable Qpid Broker - Invoke with an opened qpid.messaging.Connection.
  """
  def __init__(self, conn):
    self.conn = conn
    self.sess = self.conn.session()
    self.reply_to = "qmf.default.topic/direct.%s;{node:{type:topic}, link:{x-declare:{auto-delete:True,exclusive:True}}}" % \
        str(uuid4())
    self.reply_rx = self.sess.receiver(self.reply_to)
    self.reply_rx.capacity = 10
    self.tx = self.sess.sender("qmf.default.direct/broker")
    self.next_correlator = 1

  def close(self):
    """
    Close the proxy session.  This will not affect the connection used in creating the object.
    """
    self.sess.close()

  def _method(self, method, arguments, addr="org.apache.qpid.broker:broker:amqp-broker", timeout=10):
    props = {'method'             : 'request',
             'qmf.opcode'         : '_method_request',
             'x-amqp-0-10.app-id' : 'qmf2'}
    correlator = str(self.next_correlator)
    self.next_correlator += 1

    content = {'_object_id'   : {'_object_name' : addr},
               '_method_name' : method,
               '_arguments'   : arguments}

    message = Message(content, reply_to=self.reply_to, correlation_id=correlator,
                      properties=props, subject="broker")
    self.tx.send(message)
    response = self.reply_rx.fetch(timeout)
    self.sess.acknowledge()
    if response.properties['qmf.opcode'] == '_exception':
      raise Exception("Exception from Agent: %r" % response.content['_values'])
    if response.properties['qmf.opcode'] != '_method_response':
      raise Exception("bad response: %r" % response.properties)
    return response.content['_arguments']

  def _sendRequest(self, opcode, content):
    props = {'method'             : 'request',
             'qmf.opcode'         : opcode,
             'x-amqp-0-10.app-id' : 'qmf2'}
    correlator = str(self.next_correlator)
    self.next_correlator += 1
    message = Message(content, reply_to=self.reply_to, correlation_id=correlator,
                      properties=props, subject="broker")
    self.tx.send(message)
    return correlator

  def _doClassQuery(self, class_name):
    query = {'_what'      : 'OBJECT',
             '_schema_id' : {'_class_name' : class_name}}
    correlator = self._sendRequest('_query_request', query)
    response = self.reply_rx.fetch(10)
    if response.properties['qmf.opcode'] != '_query_response':
      raise Exception("bad response")
    items = []
    done = False
    while not done:
      for item in response.content:
        items.append(item)
      if 'partial' in response.properties:
        response = self.reply_rx.fetch(10)
      else:
        done = True
      self.sess.acknowledge()
    return items

  def _doNameQuery(self, class_name, object_name, package_name='org.apache.qpid.broker'):
    query = {'_what'      : 'OBJECT',
             '_object_id' : {'_object_name' : "%s:%s:%s" % (package_name, class_name, object_name)}}
    correlator = self._sendRequest('_query_request', query)
    response = self.reply_rx.fetch(10)
    if response.properties['qmf.opcode'] != '_query_response':
      raise Exception("bad response")
    items = []
    done = False
    while not done:
      for item in response.content:
        items.append(item)
      if 'partial' in response.properties:
        response = self.reply_rx.fetch(10)
      else:
        done = True
      self.sess.acknowledge()
    if len(items) == 1:
      return items[0]
    return None

  def _getAllBrokerObjects(self, cls):
    items = self._doClassQuery(cls.__name__.lower())
    objs = []
    for item in items:
      objs.append(cls(self, item))
    return objs

  def _getBrokerObject(self, cls, name):
    obj = self._doNameQuery(cls.__name__.lower(), name)
    if obj:
      return cls(self, obj)
    return None

  def _getSingleObject(self, cls):
    objects = self._getAllBrokerObjects(cls)
    if objects: return objects[0]
    return None

  def getBroker(self):
    """
    Get the Broker object that contains broker-scope statistics and operations.
    """
    #
    # getAllBrokerObjects is used instead of getBrokerObject(Broker, 'amqp-broker') because
    # of a bug that used to be in the broker whereby by-name queries did not return the
    # object timestamps.
    #
    return self._getSingleObject(Broker)


  def getCluster(self):
    return self._getSingleObject(Cluster)

  def getHaBroker(self):
    return self._getSingleObject(HaBroker)

  def getAllConnections(self):
    return self._getAllBrokerObjects(Connection)

  def getConnection(self, name):
    return self._getBrokerObject(Connection, name)

  def getAllSessions(self):
    return self._getAllBrokerObjects(Session)

  def getSession(self, name):
    return self._getBrokerObject(Session, name)

  def getAllSubscriptions(self):
    return self._getAllBrokerObjects(Subscription)

  def getSubscription(self, name):
    return self._getBrokerObject(Subscription, name)

  def getAllExchanges(self):
    return self._getAllBrokerObjects(Exchange)

  def getExchange(self, name):
    return self._getBrokerObject(Exchange, name)

  def getAllQueues(self):
    return self._getAllBrokerObjects(Queue)

  def getQueue(self, name):
    return self._getBrokerObject(Queue, name)

  def getAllBindings(self):
    return self._getAllBrokerObjects(Binding)

  def getAllLinks(self):
    return self._getAllBrokerObjects(Link)

  def getAcl(self):
    return self._getSingleObject(Acl)

  def echo(self, sequence, body):
    """Request a response to test the path to the management broker"""
    pass

  def connect(self, host, port, durable, authMechanism, username, password, transport):
    """Establish a connection to another broker"""
    pass

  def queueMoveMessages(self, srcQueue, destQueue, qty):
    """Move messages from one queue to another"""
    pass

  def setLogLevel(self, level):
    """Set the log level"""
    pass

  def getLogLevel(self):
    """Get the log level"""
    pass

  def setTimestampConfig(self, receive):
    """Set the message timestamping configuration"""
    pass

  def getTimestampConfig(self):
    """Get the message timestamping configuration"""
    pass

  def addExchange(self, exchange_type, name, options={}, **kwargs):
    properties = {}
    properties['exchange-type'] = exchange_type
    for k,v in options.items():
      properties[k] = v
    for k,v in kwargs.items():
      properties[k] = v
    args = {'type':       'exchange',
            'name':        name,
            'properties':  properties,
            'strict':      True}
    self._method('create', args)

  def delExchange(self, name):
    args = {'type': 'exchange', 'name': name}
    self._method('delete', args)

  def addQueue(self, name, options={}, **kwargs):
    properties = options
    for k,v in kwargs.items():
      properties[k] = v
    args = {'type':       'queue',
            'name':        name,
            'properties':  properties,
            'strict':      True}
    self._method('create', args)

  def delQueue(self, name):
    args = {'type': 'queue', 'name': name}
    self._method('delete', args)

  def bind(self, exchange, queue, key, options={}, **kwargs):
    properties = options
    for k,v in kwargs.items():
      properties[k] = v
    args = {'type':       'binding',
            'name':       "%s/%s/%s" % (exchange, queue, key),
            'properties':  properties,
            'strict':      True}
    self._method('create', args)

  def unbind(self, exchange, queue, key, **kwargs):
    args = {'type':       'binding',
            'name':       "%s/%s/%s" % (exchange, queue, key),
            'strict':      True}
    self._method('delete', args)

  def reloadAclFile(self):
    self._method('reloadACLFile', {}, "org.apache.qpid.acl:acl:org.apache.qpid.broker:broker:amqp-broker")

  def create(self, _type, name, properties, strict):
    """Create an object of the specified type"""
    pass

  def delete(self, _type, name, options):
    """Delete an object of the specified type"""
    pass

  def query(self, _type, name):
    """Query the current state of an object"""
    return self._getBrokerObject(self, _type, name)


class BrokerObject(object):
  def __init__(self, broker, content):
    self.broker = broker
    self.content = content
    self.values = content['_values']

  def __getattr__(self, key):
    if key not in self.values:
      return None
    value = self.values[key]
    if value.__class__ == dict and '_object_name' in value:
      full_name = value['_object_name']
      colon = full_name.find(':')
      if colon > 0:
        full_name = full_name[colon+1:]
        colon = full_name.find(':')
        if colon > 0:
          return full_name[colon+1:]
    return value

  def getAttributes(self):
    return self.values

  def getCreateTime(self):
    return self.content['_create_ts']

  def getDeleteTime(self):
    return self.content['_delete_ts']

  def getUpdateTime(self):
    return self.content['_update_ts']

  def update(self):
    """
    Reload the property values from the agent.
    """
    refreshed = self.broker._getBrokerObject(self.__class__, self.name)
    if refreshed:
      self.content = refreshed.content
      self.values = self.content['_values']
    else:
      raise Exception("No longer exists on the broker")

class Broker(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Cluster(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class HaBroker(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Memory(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Connection(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

  def close(self):
    pass

class Session(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Subscription(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

  def __repr__(self):
    return "subscription name undefined"

class Exchange(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Binding(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

  def __repr__(self):
    return "Binding key: %s" % self.values['bindingKey']

class Queue(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

  def purge(self, request):
    """Discard all or some messages on a queue"""
    self.broker._method("purge", {'request':request}, "org.apache.qpid.broker:queue:%s" % self.name)

  def reroute(self, request, useAltExchange, exchange, filter={}):
    """Remove all or some messages on this queue and route them to an exchange"""
    self.broker._method("reroute", {'request':request,'useAltExchange':useAltExchange,'exchange':exchange,'filter':filter},
                        "org.apache.qpid.broker:queue:%s" % self.name)

class Link(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)

class Acl(BrokerObject):
  def __init__(self, broker, values):
    BrokerObject.__init__(self, broker, values)