summaryrefslogtreecommitdiff
path: root/qpid/java/broker/src/main/java/org/apache/qpid/tools/messagestore/MessageStoreTool.java
blob: dca165fa7ea899f95240626cb38ba4aba9d45787 (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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
 *  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.
 *
 *
 */
package org.apache.qpid.tools.messagestore;

import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.qpid.configuration.Configuration;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
import org.apache.qpid.server.store.MemoryMessageStore;
import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.tools.messagestore.commands.Clear;
import org.apache.qpid.tools.messagestore.commands.Command;
import org.apache.qpid.tools.messagestore.commands.Copy;
import org.apache.qpid.tools.messagestore.commands.Dump;
import org.apache.qpid.tools.messagestore.commands.Help;
import org.apache.qpid.tools.messagestore.commands.List;
import org.apache.qpid.tools.messagestore.commands.Load;
import org.apache.qpid.tools.messagestore.commands.Quit;
import org.apache.qpid.tools.messagestore.commands.Select;
import org.apache.qpid.tools.messagestore.commands.Show;
import org.apache.qpid.tools.messagestore.commands.Move;
import org.apache.qpid.tools.messagestore.commands.Purge;
import org.apache.qpid.tools.utils.CommandParser;
import org.apache.qpid.tools.utils.Console;
import org.apache.qpid.tools.utils.SimpleCommandParser;
import org.apache.qpid.tools.utils.SimpleConsole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * MessageStoreTool.
 */
public class MessageStoreTool
{
    /** Text outputted at the start of each console.*/
    private static final String BOILER_PLATE = "MessageStoreTool - for examining Persistent Qpid Broker MessageStore instances";

    /** I/O Wrapper. */
    protected Console _console;

    /** Batch mode flag. */
    protected boolean _batchMode;

    /** Internal State object. */
    private State _state = new State();

    private HashMap<String, Command> _commands = new HashMap<String, Command>();

    /** SLF4J Logger. */
    private static Logger _devlog = LoggerFactory.getLogger(MessageStoreTool.class);

    /** Loaded configuration file. */
    private Configuration _config;

    /** Control used for main run loop. */
    private boolean _running = true;
    private boolean _initialised = false;

    //---------------------------------------------------------------------------------------------------/

    public static void main(String[] args) throws Configuration.InitException
    {

        MessageStoreTool tool = new MessageStoreTool(args);

        tool.start();
    }


    public MessageStoreTool(String[] args) throws Configuration.InitException
    {
        this(args, System.in, System.out);
    }

    public MessageStoreTool(String[] args, InputStream in, OutputStream out) throws Configuration.InitException
    {
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(in));
        BufferedWriter consoleWriter = new BufferedWriter(new OutputStreamWriter(out));

        Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook(this)));
        _batchMode = false;

        _console = new SimpleConsole(consoleWriter, consoleReader);

        _config = new Configuration();

        setOptions();
        _config.processCommandline(args);
    }


    private void setOptions()
    {
        Option help = new Option("h", "help", false, "print this message");
        Option version = new Option("v", "version", false, "print the version information and exit");
        Option configFile =
                OptionBuilder.withArgName("file").hasArg()
                        .withDescription("use given configuration file By "
                                         + "default looks for a file named "
                                         + Configuration.DEFAULT_CONFIG_FILE + " in " + Configuration.QPID_HOME)
                        .withLongOpt("config")
                        .create("c");

        _config.setOption(help);
        _config.setOption(version);
        _config.setOption(configFile);
    }

    public State getState()
    {
        return _state;
    }

    public Map<String, Command> getCommands()
    {
        return _commands;
    }

    public void setConfigurationFile(String configfile) throws Configuration.InitException
    {
        _config.loadConfig(new File(configfile));
        setup();
    }

    public Console getConsole()
    {
        return _console;
    }

    public void setConsole(Console console)
    {
        _console = console;
    }

    /**
     * Simple ShutdownHook to cleanly shutdown the databases
     */
    static class ShutdownHook implements Runnable
    {
        MessageStoreTool _tool;

        ShutdownHook(MessageStoreTool messageStoreTool)
        {
            _tool = messageStoreTool;
        }

        public void run()
        {
            _tool.quit();
        }
    }

    public void quit()
    {
        _running = false;

        if (_initialised)
        {
            ApplicationRegistry.remove(1);
        }

        _console.println("...exiting");

        _console.close();
    }

    public void setBatchMode(boolean batchmode)
    {
        _batchMode = batchmode;
    }

    /**
     * Main loop
     */
    protected void start()
    {
        setup();

        if (!_initialised)
        {
            System.exit(1);
        }

        _console.println("");

        _console.println(BOILER_PLATE);

        runCLI();
    }

    private void setup()
    {
        loadDefaultVirtualHosts();

        loadCommands();

        _state.clearAll();
    }

    private void loadCommands()
    {
        _commands.clear();
        //todo Dynamically load the classes that exis in com.redhat.etp.qpid.commands
        _commands.put("close", new Clear(this));
        _commands.put("copy", new Copy(this));
        _commands.put("dump", new Dump(this));
        _commands.put("help", new Help(this));
        _commands.put("list", new List(this));
        _commands.put("load", new Load(this));
        _commands.put("move", new Move(this));
        _commands.put("purge", new Purge(this));
        _commands.put("quit", new Quit(this));
        _commands.put("select", new Select(this));
        _commands.put("show", new Show(this));
    }

    private void loadDefaultVirtualHosts()
    {
        final File configFile = _config.getConfigFile();

        loadVirtualHosts(configFile);
    }

    private void loadVirtualHosts(File configFile)
    {

        if (!configFile.exists())
        {
            _devlog.error("Config file not found:" + configFile.getAbsolutePath());
            return;
        }
        else
        {
            _devlog.debug("using config file :" + configFile.getAbsolutePath());
        }

        try
        {
            ConfigurationFileApplicationRegistry registry = new ConfigurationFileApplicationRegistry(configFile);

            ApplicationRegistry.remove(1);

            ApplicationRegistry.initialise(registry);

            checkMessageStores();
            _initialised = true;
        }
        catch (ConfigurationException e)
        {
            _console.println("Unable to load configuration due to configuration error: " + e.getMessage());
            e.printStackTrace();
        }
        catch (Exception e)
        {
            _console.println("Unable to load configuration due to: " + e.getMessage());
            e.printStackTrace();
        }


    }

    private void checkMessageStores()
    {
        Collection<VirtualHost> vhosts = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHosts();

        boolean warning = false;
        for (VirtualHost vhost : vhosts)
        {
            if (vhost.getMessageStore() instanceof MemoryMessageStore)
            {
                _console.println("WARNING: Virtualhost '" + vhost.getName() + "' is using a MemoryMessageStore. "
                                 + "Changes will not persist.");
                warning = true;
            }
        }

        if (warning)
        {
            _console.println("");
            _console.println("Please ensure you are using the correct config file currently using '"
                             + _config.getConfigFile().getAbsolutePath() + "'");
            _console.println("New config file can be specifed by 'load <config file>' or -c on the commandline.");
            _console.println("");
        }
    }

    private void runCLI()
    {
        while (_running)
        {
            if (!_batchMode)
            {
                printPrompt();
            }

            String[] args = _console.readCommand();

            while (args != null)
            {
                exec(args);

                if (_running)
                {
                    if (!_batchMode)
                    {
                        printPrompt();
                    }

                    args = _console.readCommand();
                }
            }
        }
    }

    private void printPrompt()
    {
        _console.print(prompt());
    }


    /**
     * Execute a script (batch mode).
     *
     * @param script The file script
     */
    protected void runScripts(String script)
    {
        //Store Current State
        boolean oldBatch = _batchMode;
        CommandParser oldParser = _console.getCommandParser();
        setBatchMode(true);

        try
        {
            _devlog.debug("Running script '" + script + "'");

            _console.setCommandParser(new SimpleCommandParser(new BufferedReader(new FileReader(script))));

            start();
        }
        catch (java.io.FileNotFoundException e)
        {
            _devlog.error("Script not found: '" + script + "' due to:" + e.getMessage());
        }

        //Restore previous state
        _console.setCommandParser(oldParser);
        setBatchMode(oldBatch);
    }

    public String prompt()
    {
        String state = _state.toString();
        if (state != null && state.length() != 0)
        {
            return state + ":bdb$ ";
        }
        else
        {
            return "bdb$ ";
        }
    }

    /**
     * Execute the command.
     *
     * @param args [command, arg0, arg1...].
     */
    protected void exec(String[] args)
    {
        // Comment lines start with a #
        if (args.length == 0 || args[0].startsWith("#"))
        {
            return;
        }

        final String command = args[0];

        Command cmd = _commands.get(command);

        if (cmd == null)
        {
            _console.println("Command not understood: " + command);
        }
        else
        {
            cmd.execute(args);
        }
    }


    /**
     * Displays usage info.
     */
    protected static void help()
    {
        System.out.println(BOILER_PLATE);
        System.out.println("Usage: java " + MessageStoreTool.class + " [Options]");
        System.out.println("       [-c <broker config file>] : Defaults to \"$QPID_HOME/etc/config.xml\"");
    }


    /**
     * This class is used to store the current state of the tool.
     *
     * This is then interrogated by the various commands to augment their behaviour.
     *
     *
     */
    public static class State
    {
        private VirtualHost _vhost = null;
        private AMQQueue _queue = null;
        private Exchange _exchange = null;
        private java.util.List<Long> _msgids = null;

        public State()
        {
        }

        public void setQueue(AMQQueue queue)
        {
            _queue = queue;
        }

        public AMQQueue getQueue()
        {
            return _queue;
        }

        public void setVhost(VirtualHost vhost)
        {
            _vhost = vhost;
        }

        public VirtualHost getVhost()
        {
            return _vhost;
        }

        public Exchange getExchange()
        {
            return _exchange;
        }

        public void setExchange(Exchange exchange)
        {
            _exchange = exchange;
        }

        public String toString()
        {
            StringBuilder status = new StringBuilder();

            if (_vhost != null)
            {
                status.append(_vhost.getName());

                if (_exchange != null)
                {
                    status.append("[");
                    status.append(_exchange.getNameShortString());
                    status.append("]");

                    if (_queue != null)
                    {
                        status.append("->'");
                        status.append(_queue.getNameShortString());
                        status.append("'");

                        if (_msgids != null)
                        {
                            status.append(printMessages());
                        }
                    }
                }
            }

            return status.toString();
        }


        public String printMessages()
        {
            StringBuilder sb = new StringBuilder();

            Long previous = null;

            Long start = null;
            for (Long id : _msgids)
            {
                if (previous != null)
                {
                    if (id == previous + 1)
                    {
                        if (start == null)
                        {
                            start = previous;
                        }
                    }
                    else
                    {
                        if (start != null)
                        {
                            sb.append(",");
                            sb.append(start);
                            sb.append("-");
                            sb.append(id);
                            start = null;
                        }
                        else
                        {
                            sb.append(",");
                            sb.append(previous);
                        }
                    }
                }

                previous = id;
            }

            if (start != null)
            {
                sb.append(",");
                sb.append(start);
                sb.append("-");
                sb.append(_msgids.get(_msgids.size() - 1));
            }
            else
            {
                sb.append(",");
                sb.append(previous);
            }

            // surround list in ()
            sb.replace(0, 1, "(");
            sb.append(")");
            return sb.toString();
        }

        public void clearAll()
        {
            _vhost = null;
            clearExchange();
        }

        public void clearExchange()
        {
            _exchange = null;
            clearQueue();
        }

        public void clearQueue()
        {
            _queue = null;
            clearMessages();
        }

        public void clearMessages()
        {
            _msgids = null;
        }

        /**
         * A common location to provide parsing of the message id string
         * utilised by a number of the commands.
         * The String is comma separated list of ids that can be individual ids
         * or a range (4-10)
         *
         * @param msgString string of msg ids to parse 1,2,4-10
         */
        public void setMessages(String msgString)
        {
            StringTokenizer tok = new StringTokenizer(msgString, ",");

            if (tok.hasMoreTokens())
            {
                _msgids = new LinkedList<Long>();
            }

            while (tok.hasMoreTokens())
            {
                String next = tok.nextToken();
                if (next.contains("-"))
                {
                    Long start = Long.parseLong(next.substring(0, next.indexOf("-")));
                    Long end = Long.parseLong(next.substring(next.indexOf("-") + 1));

                    if (end >= start)
                    {
                        for (long l = start; l <= end; l++)
                        {
                            _msgids.add(l);
                        }
                    }
                }
                else
                {
                    _msgids.add(Long.parseLong(next));
                }
            }

        }

        public void setMessages(java.util.List<Long> msgids)
        {
            _msgids = msgids;
        }

        public java.util.List<Long> getMessages()
        {
            return _msgids;
        }
    }//Class State

}//Class MessageStoreTool