summaryrefslogtreecommitdiff
path: root/qpid/java/management/agent/src/main/java/org/apache/qpid/agent/Agent.java
blob: b1a4a8c93e4bdfdb2ee53666761955ff0283f227 (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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/*
 *
 * 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.agent;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.qpid.agent.binding.BindingContext;
import org.apache.qpid.agent.binding.BindingUtils;
import org.apache.qpid.agent.binding.ClassBinding;
import org.apache.qpid.agent.binding.BindingException;
import org.apache.qpid.agent.binding.MethodBinding;
import org.apache.qpid.agent.binding.ParameterBinding;
import org.apache.qpid.agent.binding.PropertyBinding;
import org.apache.qpid.agent.binding.TypeBinding;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.transport.codec.BBDecoder;
import org.apache.qpid.transport.codec.BBEncoder;
import org.apache.qpid.transport.codec.Decoder;

/**
 * The main class for interacting with the QMF bus. Objects which are to be
 * managed can be registered with the agent, as can classes to be exposed via
 * the schema.
 */
public class Agent implements MessageListener
{
    // The following are settings to configure the Agent
    protected AMQConnection connection;
    protected boolean sessionTransacted = false;
    protected int acknowledgeMode = Session.AUTO_ACKNOWLEDGE;
    protected String label;
    protected UUID systemId;
    // this list holds the objects until the agent is started
    protected List managedObjects = new ArrayList();
    protected List registeredClasses = new ArrayList();
    // The following instance variables are not
    // able to be set by the end user.
    protected Session session;
    protected MessageProducer prod;
    protected MessageConsumer cons;
    protected Queue reply;
    protected BindingContext bctx = new BindingContext();
    protected Map<Long, ManagedObject> objects = new Hashtable<Long, ManagedObject>();
    protected long bbank;
    protected long abank;
    protected static final Log log = LogFactory.getLog(Agent.class);
    protected volatile boolean inside = false;
    protected ClassLoader classLoader = null;

    public Agent()
    {
        systemId = UUID.randomUUID();
        log.debug(String.format("Agent with uid %s created", systemId
                .toString()));
    }

    public Agent(String label, UUID systemId)
    {
        this.systemId = systemId;
        this.label = label;
        log.debug(String.format("Agent with name %s and uid %s created", label,
                systemId.toString()));
    }

    public void register(ManagedObject managedObject)
    {
        Class managedClass = managedObject.getObjectClass();
        long id = managedObject.getId();
        ClassBinding cb = bctx.register(managedClass);
        managedObject.setManagedClassName(cb.getName());
        managedObject.setManagedPackageName(cb.getPackage());
        log.debug(String.format(
                "Added managed object id '%d' for package '%s' class '%s'", id,
                managedObject.getManagedPackageName(), managedObject
                        .getManagedClassName()));
        objects.put(id, managedObject);
        managedObjects.add(managedObject);
    }

    public void registerClass(Class cls)
    {
        bctx.register(cls);
        if (!registeredClasses.contains(cls))
        {
            registeredClasses.add(cls);
        }
    }

    /**
     * Stops the agents connection to the bus
     */
    public void stop()
    {
        try
        {
            cons.close();
            prod.close();
            connection.stop();
            connection.close();
            session.close();
        } catch (JMSException e)
        {
            log.error("Exception:", e);
        }
    }

    /**
     * Starts up the agent. Many bean containers may call this by default which
     * aids in deployment
     */
    public void start()
    {
        log.debug(String.format("Agent with uid %s and name %s starting",
                systemId.toString(), label));
        for (Object clsName : registeredClasses.toArray())
        {
            try
            {
                Class cls = null;
                if (String.class.isAssignableFrom(clsName.getClass()))
                {
                    cls = getClass(clsName.toString());
                } else
                {
                    cls = (Class) clsName;
                }
                this.registerClass(cls);
            } catch (Exception e)
            {
                log.error("Could not register class " + clsName);
            }
        }
        for (Object obj : managedObjects.toArray())
        {
            this.register((ManagedObject) obj);
        }
        try
        {
            session = connection.createSession(sessionTransacted,
                    acknowledgeMode);
            reply = session
                    .createQueue(String
                            .format(
                                    "direct://amq.direct//%s-%s?exclusive='True'&autodelete='True'",
                                    label, systemId));
            cons = session.createConsumer(reply);
            cons.setMessageListener(this);
            prod = session.createProducer(null);
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
        attachRequest(label, systemId);
        try
        {
            connection.start();
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
    }

    /**
     * Send an event object to the bus
     */
    public void raiseEvent(Object value, EventSeverity sev)
    {
        log.debug(String.format("Sending event of class %s with Severity %s",
                value.getClass(), sev.ordinal()));
        BBEncoder enc = this.init('e');
        ClassBinding cb = bctx.getClassBinding(value.getClass());
        String pkg = cb.getPackage();
        String cls = cb.getName();
        enc.writeStr8(pkg);
        enc.writeStr8(cls);
        enc.writeBin128(cb.getSchemaHash());
        long now = System.currentTimeMillis() * 1000000;
        enc.writeInt64(now);
        enc.writeUint8((short) sev.ordinal());
        for (PropertyBinding p : cb.getProperties())
        {
            p.getType().encode(enc, BindingUtils.get(p, value));
        }
        send(
                String.format("console.event.%d.%d.%s.%s", bbank, abank, pkg,
                        cls), enc);
    }

    public void onMessage(Message message)
    {
        if (inside)
        {
            new Throwable().printStackTrace();
        }
        inside = true;
        Decoder dec = readBody(message);
        Destination replyTo;
        try
        {
            replyTo = message.getJMSReplyTo();
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
        byte[] magic = dec.readBytes(3);
        if (magic[0] != 'A' || magic[1] != 'M' || magic[2] != '2')
        {
            throw new AgentException("bad magic: " + new String(magic));
        }
        short op = dec.readUint8();
        long seq = dec.readUint32();
        log.debug("Message recieved: " + (char) op);
        switch (op)
        {
        case 'a':
            this.handleAgentAttach(seq, replyTo, dec);
            break;
        case 'G':
            this.handleGetQuery(seq, replyTo, dec);
            break;
        case 'M':
            this.handleMethodRequest(seq, replyTo, dec);
            break;
        case 'S':
            this.handleSchemaRequest(seq, replyTo, dec);
            break;
        case 'x':
            // TODO
            break;
        default:
            throw new IllegalArgumentException("opcode: " + ((char) op));
        }
        inside = false;
    }

    protected ClassBinding getClassBinding(ManagedObject mobj)
    {
        return bctx.getClassBinding(mobj.getObjectClass());
    }

    private byte[] ensure(int capacity, byte[] body, int size)
    {
        if (capacity > body.length)
        {
            byte[] copy = new byte[capacity];
            System.arraycopy(body, 0, copy, 0, size);
            body = copy;
        }
        return body;
    }

    private Decoder readBody(Message message)
    {
        BytesMessage msg = (BytesMessage) message;
        BBDecoder dec = new BBDecoder();
        byte[] buf = new byte[1024];
        byte[] body = new byte[1024];
        int size = 0;
        int n;
        try
        {
            while ((n = msg.readBytes(buf)) > 0)
            {
                body = ensure(size + n, body, size);
                System.arraycopy(buf, 0, body, size, n);
                size += n;
            }
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
        dec.init(ByteBuffer.wrap(body, 0, size));
        return dec;
    }

    protected void handleAgentAttach(long seq, Destination replyTo, Decoder dec)
    {
        log.debug("Agent Attach Message");
        bbank = dec.readUint32();
        abank = dec.readUint32();
        try
        {
            MessageConsumer mc = session
                    .createConsumer(session
                            .createQueue(String
                                    .format(
                                            "management://qpid.management//%s-%s?routingkey='agent.%d.%d'&exclusive='True'&autodelete='True'",
                                            label, systemId, bbank, abank)));
            mc.setMessageListener(this);
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
        for (String packageName : bctx.getPackages())
        {
            packageIndication(packageName);
        }
        for (ClassBinding cb : bctx.getAllBindings())
        {
            classIndication(cb);
        }
        for (ManagedObject mo : objects.values())
        {
            content('i', seq, null, mo);
        }
    }

    protected void handleMethodRequest(long seq, Destination replyTo,
            Decoder dec)
    {
        dec.readUint64(); // first part of object-id
        long id = dec.readUint64();
        ManagedObject mo = objects.get(id);
        if (mo == null)
        {
            methodResponse(seq, replyTo, 1, String.format(
                    "no such object: 0x%x", id));
        } else
        {
            dec.readStr8(); // pkg
            dec.readStr8(); // cls
            dec.readBin128(); // hash
            String mname = dec.readStr8();
            ClassBinding cls = getClassBinding(mo);
            MethodBinding method = cls.getMethod(mname);
            if (method == null)
            {
                methodResponse(seq, replyTo, 2, String.format(
                        "no such method: %s", mname));
            } else
            {
                log.trace("Handle method: " + method.getName());
                List<ParameterBinding> params = method.getInParameters();
                Object[] args = new Object[params.size()];
                int idx = 0;
                for (ParameterBinding p : params)
                {
                    TypeBinding typeBinding = p.getType();
                    log
                            .trace(String
                                    .format(
                                            "Decoding parameter with type %s ref package %s ref class %s ",
                                            typeBinding.getCode(), typeBinding
                                                    .getRefPackage(),
                                            typeBinding.getRefClass()));
                    args[idx++] = typeBinding.decode(dec);
                    log.trace("Done");
                }
                try
                {
                    Object[] result = mo.invoke(method, args);
                    methodResponse(seq, replyTo, 0, null, method, result);
                } catch (BindingException ex)
                {
                    log
                            .error(
                                    String
                                            .format(
                                                    "An exception occured invoking method %s. Stack trace sent to console.",
                                                    method.getName()), ex);
                    StringWriter str = new StringWriter();
                    PrintWriter writer = new PrintWriter(str);
                    ex.printStackTrace(writer);
                    writer.flush();
                    methodResponse(seq, replyTo, 7, str.toString());
                }
                log.trace("Done with method: " + method.getName());
            }
        }
    }

    protected void handleGetQuery(long seq, Destination replyTo, Decoder dec)
    {
        Map<String, Object> data = dec.readMap();
        if (data.containsKey("_objectid"))
        {
            long objId = (Long) data.get("_objectid");
            log.debug("Get Request message for object id " + objId);
            ManagedObject mo = objects.get(objId);
            if (mo == null)
            {
                methodResponse(seq, replyTo, 1, String.format(
                        "no such object: 0x%x", objId));
            } else
            {
                content('g', seq, replyTo, mo);
            }
        } else if (data.containsKey("_class"))
        {
            String className = (String) data.get("_class");
            String packageName = (String) data.get("_package");
            log.debug(String.format(
                    "Get Request message for package '%s' class '%s'",
                    packageName, className));
            for (ManagedObject mo : objects.values())
            {
                if (mo.getManagedClassName().equals(className))
                {
                    if ((packageName == null) || packageName.equals("")
                            || packageName.equals(mo.getManagedPackageName()))
                    {
                        content('g', seq, replyTo, mo);
                    }
                }
            }
        } else
        {
            for (ManagedObject mo : objects.values())
            {
                content('g', seq, replyTo, mo);
            }
        }
        complete(seq, replyTo);
    }

    protected void handleSchemaRequest(long seq, Destination replyTo,
            Decoder dec)
    {
        String pkg = dec.readStr8();
        String cls = dec.readStr8();
        log.debug(String.format(
                "SchemaRequest message for package '%s' class '%s'", pkg, cls));
        ClassBinding cb = bctx.getClassBinding(pkg, cls);
        if (cb == null)
        {
            throw new AgentException("no such class: " + pkg + ", " + cls);
        }
        schemaResponse(seq, cb);
    }

    protected BBEncoder init(char opcode)
    {
        return init(opcode, 0);
    }

    protected BBEncoder init(char opcode, long sequence)
    {
        BBEncoder enc = new BBEncoder(1024);
        enc.init();
        enc.writeUint8((short) 'A');
        enc.writeUint8((short) 'M');
        enc.writeUint8((short) '2');
        enc.writeUint8((short) opcode);
        enc.writeUint32(sequence);
        return enc;
    }

    protected void send(BBEncoder enc)
    {
        send("broker", enc);
    }

    protected void send(Destination dest, BBEncoder enc)
    {
        try
        {
            byte[] buf = new byte[1024];
            BytesMessage msg = session.createBytesMessage();
            ByteBuffer slice = enc.segment();
            while (slice.hasRemaining())
            {
                int n = Math.min(buf.length, slice.remaining());
                slice.get(buf, 0, n);
                msg.writeBytes(buf, 0, n);
            }
            msg.setJMSReplyTo(reply);
            // ???: I assume this is thread safe.
            prod.send(dest, msg);
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
    }

    protected void send(String routingKey, BBEncoder enc)
    {
        try
        {
            send(session
                    .createQueue("management://qpid.management//?routingkey='"
                            + routingKey + "'"), enc);
        } catch (JMSException e)
        {
            throw new AgentException(e);
        }
    }

    protected void attachRequest(String label, UUID systemId)
    {
        BBEncoder enc = init('A');
        enc.writeStr8(label);
        enc.writeUuid(systemId);
        enc.writeUint32(0);
        enc.writeUint32(0);
        send(enc);
    }

    protected void packageIndication(String pkg)
    {
        BBEncoder enc = init('p');
        enc.writeStr8(pkg);
        send(enc);
    }

    protected void classIndication(ClassBinding cb)
    {
        BBEncoder enc = init('q');
        enc.writeUint8(cb.getKind());
        enc.writeStr8(cb.getPackage());
        enc.writeStr8(cb.getName());
        enc.writeBin128(cb.getSchemaHash()); // schema hash?
        send(enc);
    }

    protected void schemaResponse(long seq, ClassBinding cb)
    {
        BBEncoder enc = init('s', seq);
        cb.encode(enc);
        send(enc);
    }

    protected void content(char c, long seq, Destination dest, ManagedObject mo)
    {
        BBEncoder enc = init(c, seq);
        ClassBinding cb = getClassBinding(mo);
        String pkg = cb.getPackage();
        String cls = cb.getName();
        enc.writeStr8(pkg);
        enc.writeStr8(cls);
        enc.writeBin128(cb.getSchemaHash());
        long now = System.currentTimeMillis() * 1000000;
        enc.writeUint64(now);
        enc.writeUint64(now);
        enc.writeUint64(0);
        enc.writeUint64(0x0000FFFFFFFFFFFFL & ((bbank << 28) | abank));
        enc.writeUint64(mo.getId());
        for (PropertyBinding p : cb.getProperties())
        {
            p.getType().encode(enc, mo.get(p));
        }
        if (dest == null)
        {
            send(String.format("console.obj.%d.%d.%s.%s", bbank, abank, pkg,
                    cls), enc);
        } else
        {
            send(dest, enc);
        }
    }

    protected void complete(long seq, Destination dest)
    {
        BBEncoder enc = init('z', seq);
        enc.writeUint32(0);
        enc.writeStr8("");
        send(dest, enc);
    }

    protected void methodResponse(long seq, Destination dest, int status,
            String text)
    {
        methodResponse(seq, dest, status, text, null, null);
    }

    protected void methodResponse(long seq, Destination dest, int status,
            String text, MethodBinding method, Object[] result)
    {
        BBEncoder enc = init('m', seq);
        enc.writeUint32(status);
        enc.writeStr16(text == null ? "" : text);
        if (method != null)
        {
            int idx = 0;
            for (ParameterBinding p : method.getOutParameters())
            {
                p.getType().encode(enc, result[idx++]);
            }
        }
        send(dest, enc);
    }

    protected Class getClass(String className)
    {
        try
        {
            if (classLoader != null)
            {
                return classLoader.loadClass(className);
            } else
            {
                return Class.forName(className);
            }
        } catch (ClassNotFoundException e)
        {
            throw new AgentException(String.format(
                    "No class named %s was found", className), e);
        }
    }

    public String getLabel()
    {
        return label;
    }

    public void setLabel(String label)
    {
        this.label = label;
    }

    public AMQConnection getConnection()
    {
        return connection;
    }

    public void setConnection(AMQConnection connection)
    {
        this.connection = connection;
    }

    public boolean isSessionTransacted()
    {
        return sessionTransacted;
    }

    public void setSessionTransacted(boolean sessionTransacted)
    {
        this.sessionTransacted = sessionTransacted;
    }

    public void setManagedObjects(List objectList)
    {
        this.managedObjects = objectList;
    }

    public List getManagedObjects()
    {
        return managedObjects;
    }

    public void setRegisteredClasses(List objectList)
    {
        this.registeredClasses = objectList;
    }

    public List getRegisteredClasses()
    {
        return this.registeredClasses;
    }

    public static void main(String[] args) throws Exception
    {
        String broker = args[0];
        String name = args[1];
        String url = String.format(
                "amqp://guest:guest@/?brokerlist='tcp://%s'", broker);
        AMQConnection conn = new AMQConnection(url);
        Agent agent = new Agent(name, UUID.randomUUID());
        agent.setConnection(conn);
        for (int i = 2; i < args.length; i++)
        {
            Class<?> cls = Class.forName(args[i]);
            agent.register(new ManagedPOJO(cls.newInstance()));
        }
        agent.start();
        while (true)
        {
            Thread.sleep(1000);
        }
    }
}