summaryrefslogtreecommitdiff
path: root/python/commands/qpid-config
blob: 03a0fd85389cf49a4bfa529797933af664621947 (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
#!/usr/bin/env python

#
# 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.
#

import os
import getopt
import sys
import socket
import qpid
from threading       import Condition
from qpid.management import managementClient
from qpid.peer       import Closed
from qpid.connection import Connection
from qpid.util       import connect
from time            import sleep

_defspecpath  = "/usr/share/amqp/amqp.0-10.xml"
_specpath     = _defspecpath
_recursive    = False
_host         = "localhost"
_durable      = False
_fileCount    = 8
_fileSize     = 24

FILECOUNT = "qpid.file_count"
FILESIZE  = "qpid.file_size"

def Usage ():
    print "Usage:  qpid-config [OPTIONS]"
    print "        qpid-config [OPTIONS] exchanges [filter-string]"
    print "        qpid-config [OPTIONS] queues    [filter-string]"
    print "        qpid-config [OPTIONS] add exchange <type> <name> [AddExchangeOptions]"
    print "        qpid-config [OPTIONS] del exchange <name>"
    print "        qpid-config [OPTIONS] add queue <name> [AddQueueOptions]"
    print "        qpid-config [OPTIONS] del queue <name>"
    print "        qpid-config [OPTIONS] bind   <exchange-name> <queue-name> [binding-key]"
    print "        qpid-config [OPTIONS] unbind <exchange-name> <queue-name> [binding-key]"
    print
    print "Options:"
    print "    -b [ --bindings ]                         Show bindings in queue or exchange list"
    print "    -a [ --broker-addr ] Address (localhost)  Address of qpidd broker"
    print "         broker-addr is in the form:   hostname | ip-address [:<port>]"
    print "         ex:  localhost, 10.1.1.7:10000, broker-host:10000"
    print "    -s [ --spec-file] Path (" + _defspecpath + ")"
    print "                                              AMQP specification file"
    print
    print "Add Queue Options:"
    print "    --durable           Queue is durable"
    print "    --file-count N (8)  Number of files in queue's persistence journal"
    print "    --file-size  N (24) File size in pages (64Kib/page)"
    print
    print "Add Exchange Options:"
    print "    --durable           Exchange is durable"
    print
    sys.exit (1)

class Broker:
    def __init__ (self, text):
        colon = text.find (":")
        if colon == -1:
            host = text
            self.port = 5672
        else:
            host = text[:colon]
            self.port = int (text[colon+1:])
        self.host = socket.gethostbyname (host)

    def name (self):
        return self.host + ":" + str (self.port)

class BrokerManager:
    def __init__ (self):
        self.dest   = None
        self.src    = None
        self.broker = None

    def SetBroker (self, broker):
        self.broker = broker

    def ConnectToBroker (self):
        try:
            self.spec = qpid.spec.load (_specpath)
            self.sessionId = "%s.%d" % (os.uname()[1], os.getpid())
            self.conn = Connection (connect (self.broker.host, self.broker.port), self.spec)
            self.conn.start ()
            self.mclient  = managementClient (self.spec)
            self.mchannel = self.mclient.addChannel (self.conn.session(self.sessionId))
        except socket.error, e:
            print "Socket Error:", e
            sys.exit (1)
        except Closed, e:
            print "Connect Failed:", e
            sys.exit (1)

    def Disconnect (self):
        self.mclient.removeChannel (self.mchannel)

    def Overview (self):
        self.ConnectToBroker ()
        mc  = self.mclient
        mch = self.mchannel
        mc.syncWaitForStable (mch)
        exchanges = mc.syncGetObjects (mch, "exchange")
        queues    = mc.syncGetObjects (mch, "queue")
        print "Total Exchanges: %d" % len (exchanges)
        etype = {}
        for ex in exchanges:
            if ex.type not in etype:
                etype[ex.type] = 1
            else:
                etype[ex.type] = etype[ex.type] + 1
        for typ in etype:
            print "%15s: %d" % (typ, etype[typ])

        print
        print "   Total Queues: %d" % len (queues)
        _durable = 0
        for queue in queues:
            if queue.durable:
                _durable = _durable + 1
        print "        durable: %d" % _durable
        print "    non-durable: %d" % (len (queues) - _durable)

    def ExchangeList (self, filter):
        self.ConnectToBroker ()
        mc  = self.mclient
        mch = self.mchannel
        mc.syncWaitForStable (mch)
        exchanges = mc.syncGetObjects (mch, "exchange")
        print "Type      Bindings  Exchange Name"
        print "============================================="
        for ex in exchanges:
            if self.match (ex.name, filter):
                print "%-10s%5d     %s" % (ex.type, ex.bindings, ex.name)

    def ExchangeListRecurse (self, filter):
        self.ConnectToBroker ()
        mc  = self.mclient
        mch = self.mchannel
        mc.syncWaitForStable (mch)
        exchanges = mc.syncGetObjects (mch, "exchange")
        bindings  = mc.syncGetObjects (mch, "binding")
        queues    = mc.syncGetObjects (mch, "queue")
        for ex in exchanges:
            if self.match (ex.name, filter):
                print "Exchange '%s' (%s)" % (ex.name, ex.type)
                for bind in bindings:
                    if bind.exchangeRef == ex.id:
                        qname = "<unknown>"
                        queue = self.findById (queues, bind.queueRef)
                        if queue != None:
                            qname = queue.name
                        print "    bind [%s] => %s" % (bind.bindingKey, qname)
            

    def QueueList (self, filter):
        self.ConnectToBroker ()
        mc  = self.mclient
        mch = self.mchannel
        mc.syncWaitForStable (mch)
        queues   = mc.syncGetObjects (mch, "queue")
        journals = mc.syncGetObjects (mch, "journal")
        print "                                      Store Size"
        print "Durable  AutoDel  Excl  Bindings  (files x file pages)  Queue Name"
        print "==========================================================================================="
        for q in queues:
            if self.match (q.name, filter):
                args = q.arguments
                if q.durable and FILESIZE in args and FILECOUNT in args:
                    fs = int (args[FILESIZE])
                    fc = int (args[FILECOUNT])
                    print "%4c%9c%7c%10d%11dx%-14d%s" % \
                        (YN (q.durable), YN (q.autoDelete),
                         YN (q.exclusive), q.bindings, fc, fs, q.name)
                else:
                    if not _durable:
                        print "%4c%9c%7c%10d                          %s" % \
                            (YN (q.durable), YN (q.autoDelete),
                             YN (q.exclusive), q.bindings, q.name)

    def QueueListRecurse (self, filter):
        self.ConnectToBroker ()
        mc  = self.mclient
        mch = self.mchannel
        mc.syncWaitForStable (mch)
        exchanges = mc.syncGetObjects (mch, "exchange")
        bindings  = mc.syncGetObjects (mch, "binding")
        queues    = mc.syncGetObjects (mch, "queue")
        for queue in queues:
            if self.match (queue.name, filter):
                print "Queue '%s'" % queue.name
                for bind in bindings:
                    if bind.queueRef == queue.id:
                        ename = "<unknown>"
                        ex    = self.findById (exchanges, bind.exchangeRef)
                        if ex != None:
                            ename = ex.name
                            if ename == "":
                                ename = "''"
                        print "    bind [%s] => %s" % (bind.bindingKey, ename)

    def AddExchange (self, args):
        if len (args) < 2:
            Usage ()
        self.ConnectToBroker ()
        etype = args[0]
        ename = args[1]

        try:
            self.channel.exchange_declare (exchange=ename, type=etype, durable=_durable)
        except Closed, e:
            print "Failed:", e

    def DelExchange (self, args):
        if len (args) < 1:
            Usage ()
        self.ConnectToBroker ()
        ename = args[0]

        try:
            self.channel.exchange_delete (exchange=ename)
        except Closed, e:
            print "Failed:", e

    def AddQueue (self, args):
        if len (args) < 1:
            Usage ()
        self.ConnectToBroker ()
        qname    = args[0]
        declArgs = {}
        if _durable:
            declArgs[FILECOUNT] = _fileCount
            declArgs[FILESIZE]  = _fileSize

        try:
            self.channel.queue_declare (queue=qname, durable=_durable, arguments=declArgs)
        except Closed, e:
            print "Failed:", e

    def DelQueue (self, args):
        if len (args) < 1:
            Usage ()
        self.ConnectToBroker ()
        qname = args[0]

        try:
            self.channel.queue_delete (queue=qname)
        except Closed, e:
            print "Failed:", e

    def Bind (self, args):
        if len (args) < 2:
            Usage ()
        self.ConnectToBroker ()
        ename = args[0]
        qname = args[1]
        key   = ""
        if len (args) > 2:
            key = args[2]

        try:
            self.channel.queue_bind (queue=qname, exchange=ename, routing_key=key)
        except Closed, e:
            print "Failed:", e

    def Unbind (self, args):
        if len (args) < 2:
            Usage ()
        self.ConnectToBroker ()
        ename = args[0]
        qname = args[1]
        key   = ""
        if len (args) > 2:
            key = args[2]

        try:
            self.channel.queue_unbind (queue=qname, exchange=ename, routing_key=key)
        except Closed, e:
            print "Failed:", e

    def findById (self, items, id):
        for item in items:
            if item.id == id:
                return item
        return None

    def match (self, name, filter):
        if filter == "":
            return True
        if name.find (filter) == -1:
            return False
        return True

def YN (bool):
    if bool:
        return 'Y'
    return 'N'

##
## Main Program
##

try:
    longOpts = ("durable", "spec-file=", "bindings", "broker-addr=", "file-count=", "file-size=")
    (optlist, cargs) = getopt.gnu_getopt (sys.argv[1:], "s:a:b", longOpts)
except:
    Usage ()

for opt in optlist:
    if opt[0] == "-s" or opt[0] == "--spec-file":
        _specpath = opt[1]
    if opt[0] == "-b" or opt[0] == "--bindings":
        _recursive = True
    if opt[0] == "-a" or opt[0] == "--broker-addr":
        _host = opt[1]
    if opt[0] == "--durable":
        _durable = True
    if opt[0] == "--file-count":
        _fileCount = int (opt[1])
    if opt[0] == "--file-size":
        _fileSize = int (opt[1])

nargs = len (cargs)
bm    = BrokerManager ()
bm.SetBroker (Broker (_host))

if nargs == 0:
    bm.Overview ()
else:
    cmd = cargs[0]
    modifier = ""
    if nargs > 1:
        modifier = cargs[1]
    if cmd[0] == 'e':
        if _recursive:
            bm.ExchangeListRecurse (modifier)
        else:
            bm.ExchangeList (modifier)
    elif cmd[0] == 'q':
        if _recursive:
            bm.QueueListRecurse (modifier)
        else:
            bm.QueueList (modifier)
    elif cmd == "add":
        if modifier == "exchange":
            bm.AddExchange (cargs[2:])
        elif modifier == "queue":
            bm.AddQueue (cargs[2:])
        else:
            Usage ()
    elif cmd == "del":
        if modifier == "exchange":
            bm.DelExchange (cargs[2:])
        elif modifier == "queue":
            bm.DelQueue (cargs[2:])
        else:
            Usage ()
    elif cmd == "bind":
        bm.Bind (cargs[1:])
    elif cmd == "unbind":
        bm.Unbind (cargs[1:])
    else:
        Usage ()
bm.Disconnect()