summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/CollocatedRequestHandler.java
blob: 4c79b2e3c58690f0ff3067dfcfe4b88222d34d0c (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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package IceInternal;

public class CollocatedRequestHandler implements RequestHandler, ResponseHandler
{
    class InvokeAll extends DispatchWorkItem
    {
        public
        InvokeAll(OutgoingMessageCallback out, BasicStream os, int requestId, int invokeNum, boolean batch)
        {
            _out = out;
            _os = os;
            _requestId = requestId;
            _invokeNum = invokeNum;
            _batch = batch;
        }

        @Override
        public void
        run()
        {
            if(sent(_out))
            {
                invokeAll(_os, _requestId, _invokeNum, _batch);
            }
        }

        private final OutgoingMessageCallback _out;
        private final BasicStream _os;
        private final int _requestId;
        private final int _invokeNum;
        private final boolean _batch;
    };

    class InvokeAllAsync extends DispatchWorkItem
    {
        public InvokeAllAsync(OutgoingAsyncMessageCallback outAsync, BasicStream os, int requestId, int invokeNum,
                              boolean batch)
        {
            _outAsync = outAsync;
            _os = os;
            _requestId = requestId;
            _invokeNum = invokeNum;
            _batch = batch;
        }

        @Override
        public void
        run()
        {
            if(sentAsync(_outAsync))
            {
                invokeAll(_os, _requestId, _invokeNum, _batch);
            }
        }

        private final OutgoingAsyncMessageCallback _outAsync;
        private final BasicStream _os;
        private final int _requestId;
        private final int _invokeNum;
        private final boolean _batch;
    };

    private void
    fillInValue(BasicStream os, int pos, int value)
    {
        os.rewriteInt(pos, value);
    }

    public
    CollocatedRequestHandler(Reference ref, Ice.ObjectAdapter adapter)
    {
        _reference = ref;
        _dispatcher = ref.getInstance().initializationData().dispatcher != null;
        _response = _reference.getMode() == Reference.ModeTwoway;
        _adapter = (Ice.ObjectAdapterI)adapter;

        _logger = _reference.getInstance().initializationData().logger; // Cached for better performance.
        _traceLevels = _reference.getInstance().traceLevels(); // Cached for better performance.
        _batchAutoFlush = ref.getInstance().initializationData().properties.getPropertyAsIntWithDefault(
            "Ice.BatchAutoFlush", 1) > 0;
        _requestId = 0;
        _batchStreamInUse = false;
        _batchRequestNum = 0;
        _batchStream = new BasicStream(ref.getInstance(), Protocol.currentProtocolEncoding, _batchAutoFlush);
    }

    @Override
    synchronized public void
    prepareBatchRequest(BasicStream os)
    {
        waitStreamInUse();
        if(_batchStream.isEmpty())
        {
            try
            {
                _batchStream.writeBlob(Protocol.requestBatchHdr);
            }
            catch(Ice.LocalException ex)
            {
                throw ex;
            }
        }

        _batchStreamInUse = true;
        _batchMarker = _batchStream.size();
        _batchStream.swap(os);
    }

    @Override
    public void
    finishBatchRequest(BasicStream os)
    {
        try
        {
            synchronized(this)
            {
                _batchStream.swap(os);

                if(_batchAutoFlush & (_batchStream.size() > _reference.getInstance().messageSizeMax()))
                {
                    //
                    // Temporarily save the last request.
                    //
                    byte[] lastRequest = new byte[_batchStream.size() - _batchMarker];
                    Buffer buffer = _batchStream.getBuffer();
                    buffer.b.position(_batchMarker);
                    buffer.b.get(lastRequest);
                    _batchStream.resize(_batchMarker, false);

                    final int invokeNum = _batchRequestNum;
                    final BasicStream stream = new BasicStream(_reference.getInstance(),
                                                               Protocol.currentProtocolEncoding,
                                                               _batchAutoFlush);
                    stream.swap(_batchStream);

                    _adapter.getThreadPool().dispatch(
                        new DispatchWorkItem()
                        {
                            @Override
                            public void
                            run()
                            {
                                CollocatedRequestHandler.this.invokeAll(stream, 0, invokeNum, true);
                            }
                        });

                    //
                    // Reset the batch.
                    //
                    _batchRequestNum = 0;
                    _batchMarker = 0;

                    //
                    // Check again if the last request doesn't exceed what we can send with the auto flush
                    //
                    if(Protocol.requestBatchHdr.length + lastRequest.length > _reference.getInstance().messageSizeMax())
                    {
                        Ex.throwMemoryLimitException(Protocol.requestBatchHdr.length + lastRequest.length,
                                                     _reference.getInstance().messageSizeMax());
                    }

                    //
                    // Start a new batch with the last message that caused us to go over the limit.
                    //
                    _batchStream.writeBlob(Protocol.requestBatchHdr);
                    _batchStream.writeBlob(lastRequest);
                }

                //
                // Increment the number of requests in the batch.
                //
                assert(_batchStreamInUse);
                ++_batchRequestNum;
                _batchStreamInUse = false;
                notifyAll();
            }
        }
        catch(Ice.LocalException ex)
        {
            abortBatchRequest();
            throw ex;
        }
    }

    @Override
    synchronized public void
    abortBatchRequest()
    {
        BasicStream dummy = new BasicStream(_reference.getInstance(), Protocol.currentProtocolEncoding,
                                            _batchAutoFlush);
        _batchStream.swap(dummy);
        _batchRequestNum = 0;
        _batchMarker = 0;

        assert(_batchStreamInUse);
        _batchStreamInUse = false;
        notifyAll();
    }

    @Override
    public boolean
    sendRequest(OutgoingMessageCallback out)
    {
        out.invokeCollocated(this);
        return !_response && _reference.getInvocationTimeout() == 0;
    }

    @Override
    public int
    sendAsyncRequest(OutgoingAsyncMessageCallback outAsync)
    {
        return outAsync.__invokeCollocated(this);
    }

    @Override
    synchronized public boolean
    requestCanceled(OutgoingMessageCallback out, Ice.LocalException ex)
    {
        Integer requestId = _sendRequests.get(out);
        if(requestId != null)
        {
            if(requestId > 0)
            {
                _requests.remove(requestId);
            }
            out.finished(ex);
            _sendRequests.remove(out);
            return true;
        }
        else if(out instanceof Outgoing)
        {
            Outgoing o = (Outgoing)out;
            assert(o != null);
            for(java.util.Map.Entry<Integer, Outgoing> e : _requests.entrySet())
            {
                if(e.getValue() == o)
                {
                    out.finished(ex);
                    _requests.remove(e.getKey());
                    return true; // We're done.
                }
            }
        }
        return false;
    }

    @Override
    synchronized public boolean
    asyncRequestCanceled(OutgoingAsyncMessageCallback outAsync, Ice.LocalException ex)
    {
        Integer requestId = _sendAsyncRequests.get(outAsync);
        if(requestId != null)
        {
            if(requestId > 0)
            {
                _asyncRequests.remove(requestId);
            }
            _sendAsyncRequests.remove(outAsync);
            outAsync.__dispatchInvocationCancel(ex, _reference.getInstance().clientThreadPool(), null);
            return true; // We're done
        }

        if(outAsync instanceof OutgoingAsync)
        {
            OutgoingAsync o = (OutgoingAsync)outAsync;
            assert(o != null);
            for(java.util.Map.Entry<Integer, OutgoingAsync> e : _asyncRequests.entrySet())
            {
                if(e.getValue() == o)
                {
                    _asyncRequests.remove(e.getKey());
                    outAsync.__dispatchInvocationCancel(ex, _reference.getInstance().clientThreadPool(), null);
                    return true; // We're done
                }
            }
        }
        return false;
    }

    public void
    invokeRequest(Outgoing out)
    {
        int requestId = 0;
        if(_reference.getInvocationTimeout() > 0 || _response)
        {
            synchronized(this)
            {
                if(_response)
                {
                    requestId = ++_requestId;
                    _requests.put(requestId, out);
                }
                if(_reference.getInvocationTimeout() > 0)
                {
                    _sendRequests.put(out, requestId);
                }
            }
        }

        out.attachCollocatedObserver(_adapter, requestId);

        if(_reference.getInvocationTimeout() > 0)
        {
            // Don't invoke from the user thread, invocation timeouts wouldn't work otherwise.
            _adapter.getThreadPool().dispatch(new InvokeAll(out, out.os(), requestId, 1, false));
        }
        else if(_dispatcher)
        {
            _adapter.getThreadPool().dispatchFromThisThread(new InvokeAll(out, out.os(), requestId, 1, false));
        }
        else // Optimization: directly call invokeAll if there's no dispatcher.
        {
            out.sent();
            invokeAll(out.os(), requestId, 1, false);
        }
    }

    public int
    invokeAsyncRequest(OutgoingAsync outAsync)
    {
        int requestId = 0;
        if(_reference.getInvocationTimeout() > 0 || _response)
        {
            synchronized(this)
            {
                if(_response)
                {
                    requestId = ++_requestId;
                    _asyncRequests.put(requestId, outAsync);
                }
                if(_reference.getInvocationTimeout() > 0)
                {
                    _sendAsyncRequests.put(outAsync, requestId);
                }
            }
        }

        outAsync.__attachCollocatedObserver(_adapter, requestId);

        _adapter.getThreadPool().dispatch(new InvokeAllAsync(outAsync, outAsync.__getOs(), requestId, 1, false));

        return AsyncStatus.Queued;
    }

    public void
    invokeBatchRequests(BatchOutgoing out)
    {
        int invokeNum;
        synchronized(this)
        {
            waitStreamInUse();
            invokeNum = _batchRequestNum;

            if(_batchRequestNum > 0)
            {
                if(_reference.getInvocationTimeout() > 0)
                {
                    _sendRequests.put(out, 0);
                }

                assert(!_batchStream.isEmpty());
                _batchStream.swap(out.os());

                //
                // Reset the batch stream.
                //
                BasicStream dummy = new BasicStream(_reference.getInstance(), Protocol.currentProtocolEncoding,
                                                    _batchAutoFlush);
                _batchStream.swap(dummy);
                _batchRequestNum = 0;
                _batchMarker = 0;
            }
        }

        out.attachCollocatedObserver(_adapter, 0);

        if(invokeNum > 0)
        {
            if(_reference.getInvocationTimeout() > 0)
            {
                _adapter.getThreadPool().dispatch(new InvokeAll(out, out.os(), 0, invokeNum, true));
            }
            else if(_dispatcher)
            {
                _adapter.getThreadPool().dispatchFromThisThread(new InvokeAll(out, out.os(), 0, invokeNum, true));
            }
            else // Optimization: directly call invokeAll if there's no dispatcher.
            {
                out.sent();
                invokeAll(out.os(), 0, invokeNum, true);
            }
        }
        else
        {
            out.sent();
        }
    }

    public int
    invokeAsyncBatchRequests(BatchOutgoingAsync outAsync)
    {
        int invokeNum;
        synchronized(this)
        {
            waitStreamInUse();

            invokeNum = _batchRequestNum;
            if(_batchRequestNum > 0)
            {
                if(_reference.getInvocationTimeout() > 0)
                {
                    _sendAsyncRequests.put(outAsync, 0);
                }

                assert(!_batchStream.isEmpty());
                _batchStream.swap(outAsync.__getOs());

                //
                // Reset the batch stream.
                //
                BasicStream dummy = new BasicStream(_reference.getInstance(), Protocol.currentProtocolEncoding,
                                                    _batchAutoFlush);
                _batchStream.swap(dummy);
                _batchRequestNum = 0;
                _batchMarker = 0;
            }
        }

        outAsync.__attachCollocatedObserver(_adapter, 0);

        if(invokeNum > 0)
        {
            _adapter.getThreadPool().dispatch(new InvokeAllAsync(outAsync, outAsync.__getOs(), 0, invokeNum, true));
            return AsyncStatus.Queued;
        }
        else if(outAsync.__sent())
        {
            return AsyncStatus.Sent | AsyncStatus.InvokeSentCallback;
        }
        else
        {
            return AsyncStatus.Sent;
        }
    }

    @Override
    public void
    sendResponse(int requestId, BasicStream os, byte status)
    {
        OutgoingAsync outAsync = null;
        synchronized(this)
        {
            assert(_response);

            os.pos(Protocol.replyHdr.length + 4);

            if(_traceLevels.protocol >= 1)
            {
                fillInValue(os, 10, os.size());
                TraceUtil.traceRecv(os, _logger, _traceLevels);
            }

            Outgoing out = _requests.get(requestId);
            if(out != null)
            {
                out.finished(os);
                _requests.remove(requestId);
            }
            else
            {
                outAsync = _asyncRequests.get(requestId);
                if(outAsync != null)
                {
                    _asyncRequests.remove(requestId);
                }
            }
        }

        if(outAsync != null)
        {
            outAsync.__finished(os);
        }
        _adapter.decDirectCount();
    }

    @Override
    public void
    sendNoResponse()
    {
        _adapter.decDirectCount();
    }

    @Override
    public boolean
    systemException(int requestId, Ice.SystemException ex)
    {
        handleException(requestId, ex);
        _adapter.decDirectCount();
        return true;
    }

    @Override
    public void
    invokeException(int requestId, Ice.LocalException ex, int invokeNum)
    {
        if(requestId > 0)
        {
            OutgoingAsync outAsync = null;
            synchronized(this)
            {
                Outgoing out = _requests.remove(requestId);
                if(out != null)
                {
                    out.finished(ex);
                }
                else
                {
                    outAsync = _asyncRequests.remove(requestId);
                }
            }
            if(outAsync != null)
            {
                outAsync.__finished(ex);
            }
        }
        _adapter.decDirectCount();
    }

    @Override
    public Reference
    getReference()
    {
        return _reference;
    }

    @Override
    public Ice.ConnectionI
    getConnection()
    {
        return null;
    }

    @Override
    public Ice.ConnectionI
    waitForConnection()
    {
        return null;
    }

    boolean
    sent(OutgoingMessageCallback out)
    {
        if(_reference.getInvocationTimeout() > 0)
        {
            synchronized(this)
            {
                if(_sendRequests.remove(out) == null)
                {
                    return false; // The request timed-out.
                }
            }
        }
        out.sent();
        return true;
    }

    boolean
    sentAsync(OutgoingAsyncMessageCallback outAsync)
    {
        if(_reference.getInvocationTimeout() > 0)
        {
            synchronized(this)
            {
                if(_sendAsyncRequests.remove(outAsync) == null)
                {
                    return false; // The request timed-out.
                }
            }
        }
        if(outAsync.__sent())
        {
            outAsync.__invokeSent();
        }
        return true;
    }

    void
    invokeAll(BasicStream os, int requestId, int invokeNum, boolean batch)
    {
        if(batch)
        {
            os.pos(Protocol.requestBatchHdr.length);
        }
        else
        {
            os.pos(Protocol.requestHdr.length);
        }

        if(_traceLevels.protocol >= 1)
        {
            fillInValue(os, 10, os.size());
            if(requestId > 0)
            {
                fillInValue(os, Protocol.headerSize, requestId);
            }
            else if(batch)
            {
                fillInValue(os, Protocol.headerSize, invokeNum);
            }
            TraceUtil.traceSend(os, _logger, _traceLevels);
        }

        ServantManager servantManager = _adapter.getServantManager();
        try
        {
            while(invokeNum > 0)
            {
                try
                {
                    _adapter.incDirectCount();
                }
                catch(Ice.ObjectAdapterDeactivatedException ex)
                {
                    handleException(requestId, ex);
                    return;
                }

                Incoming in = new Incoming(_reference.getInstance(), this, null, _adapter, _response, (byte)0,
                                           requestId);
                in.invoke(servantManager, os);
                --invokeNum;
            }
        }
        catch(Ice.LocalException ex)
        {
            invokeException(requestId, ex, invokeNum); // Fatal invocation exception
        }
        catch(java.lang.AssertionError ex) // Upon assertion, we print the stack trace.
        {
            Ice.UnknownException uex = new Ice.UnknownException(ex);
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            uex.unknown = sw.toString();
            _logger.error(uex.unknown);
            invokeException(requestId, uex, invokeNum);
        }
        catch(java.lang.OutOfMemoryError ex)
        {
            Ice.UnknownException uex = new Ice.UnknownException(ex);
            java.io.StringWriter sw = new java.io.StringWriter();
            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
            ex.printStackTrace(pw);
            pw.flush();
            uex.unknown = sw.toString();
            _logger.error(uex.unknown);
            invokeException(requestId, uex, invokeNum);
        }
    }

    void
    handleException(int requestId, Ice.Exception ex)
    {
        if(requestId == 0)
        {
            return; // Ignore exception for oneway messages.
        }

        OutgoingAsync outAsync = null;
        synchronized(this)
        {
            Outgoing out = _requests.get(requestId);
            if(out != null)
            {
                out.finished(ex);
                _requests.remove(requestId);
            }
            else
            {
                outAsync = _asyncRequests.get(requestId);
                if(outAsync != null)
                {
                    _asyncRequests.remove(requestId);
                }
            }
        }

        if(outAsync != null)
        {
            outAsync.__finished(ex);
        }
    }

    private void
    waitStreamInUse()
    {
        //
        // This is similar to a mutex lock in that the stream is
        // only "locked" while marshaling. As such we don't permit the wait
        // to be interrupted. Instead the interrupted status is saved and
        // restored.
        //
        boolean interrupted = false;
        while(_batchStreamInUse)
        {
            try
            {
                wait();
            }
            catch(InterruptedException ex)
            {
                interrupted = true;
            }
        }
        //
        // Restore the interrupted flag if we were interrupted.
        //
        if(interrupted)
        {
            Thread.currentThread().interrupt();
        }
    }

    private final Reference _reference;
    private final boolean _dispatcher;
    private final boolean _response;
    private final Ice.ObjectAdapterI _adapter;
    private final Ice.Logger _logger;
    private final TraceLevels _traceLevels;
    private boolean _batchAutoFlush;

    private int _requestId;

    private java.util.Map<OutgoingMessageCallback, Integer> _sendRequests =
        new java.util.HashMap<OutgoingMessageCallback, Integer>();
    private java.util.Map<OutgoingAsyncMessageCallback, Integer> _sendAsyncRequests =
        new java.util.HashMap<OutgoingAsyncMessageCallback, Integer>();

    private java.util.Map<Integer, Outgoing> _requests = new java.util.HashMap<Integer, Outgoing>();
    private java.util.Map<Integer, OutgoingAsync> _asyncRequests = new java.util.HashMap<Integer, OutgoingAsync>();

    private BasicStream _batchStream;
    private boolean _batchStreamInUse;
    private int _batchRequestNum;
    private int _batchMarker;
}