summaryrefslogtreecommitdiff
path: root/java/src/IceGrid/DiscoveryPluginI.java
blob: 6dea39c4e895ea661b5c3889f73b74d53c409fe1 (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
// **********************************************************************
//
// 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 IceGrid;

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

class DiscoveryPluginI implements Ice.Plugin
{
    abstract private class Request
    {
        Request(LocatorI locator)
        {
            _locator = locator;
        }

        abstract void
        invoke(Ice.LocatorPrx locator);

        abstract void
        response(Ice.ObjectPrx locator);

        LocatorI _locator;
        Ice.LocatorPrx _locatorPrx;
    };

    private class LocatorI extends Ice._LocatorDisp
    {
        LocatorI(LookupPrx lookup, Ice.Properties properties)
        {
            _lookup = lookup;
            _timeout = properties.getPropertyAsIntWithDefault("IceGridDiscovery.Timeout", 300) * 1000;
            _retryCount = properties.getPropertyAsIntWithDefault("IceGridDiscovery.RetryCount",3);
            _timer = IceInternal.Util.getInstance(lookup.ice_getCommunicator()).timer();
            _instanceName = properties.getProperty("IceGridDiscovery.InstanceName");
            _warned = false;
            _locator = lookup.ice_getCommunicator().getDefaultLocator();
            _pendingRetryCount = 0;
        }

        public void
        setLookupReply(LookupReplyPrx lookupReply)
        {
            _lookupReply = lookupReply;
        }

        public synchronized void
        findObjectById_async(Ice.AMD_Locator_findObjectById amdCB, Ice.Identity id, Ice.Current curr)
        {
            invoke(null, new ObjectRequest(this, id, amdCB));
        }

        public synchronized void
        findAdapterById_async(Ice.AMD_Locator_findAdapterById amdCB, String adapterId, Ice.Current curr)
        {
            invoke(null, new AdapterRequest(this, adapterId, amdCB));
        }


         public synchronized Ice.LocatorRegistryPrx
         getRegistry(Ice.Current current)
         {
            Ice.LocatorPrx locator;
            if(_locator != null)
            {
                queueRequest(null); // Search for locator if not already doing so.
                while(_pendingRetryCount > 0)
                {
                    try
                    {
                        wait();
                    }
                    catch(java.lang.InterruptedException ex)
                    {
                    }
                }
            }
            locator = _locator;
            return locator != null ? locator.getRegistry() : null;
         }

        public synchronized void
        foundLocator(LocatorPrx locator)
        {
            if(locator == null)
            {
                return;
            }

            //
            // If we already have a locator assigned, ensure the given locator
            // has the same identity, otherwise ignore it.
            //
            if(_locator != null && !locator.ice_getIdentity().category.equals(_locator.ice_getIdentity().category))
            {
                if(!_warned)
                {
                    _warned = true; // Only warn once

                    locator.ice_getCommunicator().getLogger().warning(
                        "received IceGrid locator with different instance name:\n" +
                        "using = `" + _locator.ice_getIdentity().category + "'\n" +
                        "received = `" + locator.ice_getIdentity().category + "'\n" +
                        "This is typically the case if multiple IceGrid registries with different " +
                        "nstance names are deployed and the property `IceGridDiscovery.InstanceName'" +
                        "is not set.");
                }
                return;
            }

            if(_pendingRetryCount > 0) // No need to retry, we found a locator
            {
                _future.cancel(false);
                _future = null;

                _pendingRetryCount = 0;
            }

            if(_locator != null)
            {
                //
                // We found another locator replica, append its endpoints to the
                // current locator proxy endpoints.
                //
                List<Ice.Endpoint> newEndpoints = new ArrayList<Ice.Endpoint>(
                    Arrays.asList(_locator.ice_getEndpoints()));
                for(Ice.Endpoint p : locator.ice_getEndpoints())
                {
                    //
                    // Only add endpoints if not already in the locator proxy endpoints
                    //
                    boolean found = false;
                    for(Ice.Endpoint q : newEndpoints)
                    {
                        if (p.equals(q))
                        {
                            found = true;
                            break;
                        }
                    }
                    if(!found)
                    {
                        newEndpoints.add(p);
                    }

                }
                _locator = (LocatorPrx)_locator.ice_endpoints(
                    newEndpoints.toArray(new Ice.Endpoint[newEndpoints.size()]));
            }
            else
            {
                _locator = locator;
                if(_instanceName.isEmpty())
                {
                    _instanceName = _locator.ice_getIdentity().category;
                }
            }

            //
            // Send pending requests if any.
            //
            for(Request req : _pendingRequests)
            {
                req.invoke(_locator);
            }
            _pendingRequests.clear();
            notifyAll();
        }


        public synchronized void
        invoke(Ice.LocatorPrx locator, Request request)
        {
            if(_locator != null && !(_locator.equals(locator)))
            {
                request.invoke(_locator);
            }
            else
            {
                _locator = null;
                queueRequest(request);
            }
        }

        private Runnable _retryTask = new Runnable()
        {
            public void run()
            {
                synchronized(LocatorI.this)
                {
                    if(--_pendingRetryCount > 0)
                    {
                        _lookup.begin_findLocator(_instanceName, _lookupReply); // Send multicast request.
                        _future = _timer.schedule(_retryTask, _timeout, java.util.concurrent.TimeUnit.MILLISECONDS);
                    }
                    else
                    {
                        assert !_pendingRequests.isEmpty();
                        for(Request req : _pendingRequests)
                        {
                            req.response(null);
                        }
                        _pendingRequests.clear();
                        notifyAll();

                    }
                }

            }
        };

        private void
        queueRequest(Request request)
        {
            if(request != null)
            {
                _pendingRequests.add(request);
            }

            if(_pendingRetryCount == 0) // No request in progress
            {
                _pendingRetryCount = _retryCount;
                _lookup.begin_findLocator(_instanceName, _lookupReply); // Send multicast request.
                _future = _timer.schedule(_retryTask, _timeout, java.util.concurrent.TimeUnit.MILLISECONDS);
            }
        }

        private final LookupPrx _lookup;
        private final int _timeout;
        private java.util.concurrent.Future<?> _future;
        private final java.util.concurrent.ScheduledExecutorService _timer;
        private final int _retryCount;

        private String _instanceName;
        private boolean _warned;
        private LookupReplyPrx _lookupReply;
        private Ice.LocatorPrx _locator;

        private int _pendingRetryCount;
        private List<Request> _pendingRequests = new ArrayList<Request>();;
    };

    private class LookupReplyI extends _LookupReplyDisp
    {
        LookupReplyI(LocatorI locator)
        {
            _locator = locator;
        }

        public void
        foundLocator(LocatorPrx locator, Ice.Current curr)
        {
            _locator.foundLocator(locator);
        }

        private final LocatorI _locator;
    };

    class ObjectRequest extends Request
    {
        ObjectRequest(LocatorI locator, Ice.Identity id, Ice.AMD_Locator_findObjectById amdCB)
        {
            super(locator);
            _id = id;
            _amdCB = amdCB;
        }

        void
        invoke(Ice.LocatorPrx l)
        {
            _locatorPrx = l;
            l.begin_findObjectById(_id,
                new Ice.Callback_Locator_findObjectById() {
                    public void
                    response(Ice.ObjectPrx proxy)
                    {
                        ObjectRequest.this.response(proxy);
                    }

                    public void
                    exception(Ice.UserException ex)
                    {
                        ObjectRequest.this.exception(ex);
                    }

                    public void
                    exception(Ice.LocalException ex)
                    {
                        ObjectRequest.this.exception(ex);
                    }
                });
        }

        void
        response(Ice.ObjectPrx prx)
        {
            _amdCB.ice_response(prx);
        }

        void
        exception(Exception ex)
        {
            _locator.invoke(_locatorPrx, this);
        }

        private final Ice.Identity _id;
        private final Ice.AMD_Locator_findObjectById _amdCB;
    };

    class AdapterRequest extends Request
    {

        AdapterRequest(LocatorI locator, String adapterId, Ice.AMD_Locator_findAdapterById amdCB) {
            super(locator);
            _adapterId = adapterId;
            _amdCB = amdCB;
        }

        void
        invoke(Ice.LocatorPrx l)
        {
            _locatorPrx = l;
            l.begin_findAdapterById(_adapterId,
                new Ice.Callback_Locator_findAdapterById()
                {
                    public void
                    response(Ice.ObjectPrx proxy)
                    {
                        AdapterRequest.this.response(proxy);
                    }

                    public void
                    exception(Ice.UserException ex)
                    {
                        AdapterRequest.this.exception(ex);
                    }

                    public void
                    exception(Ice.LocalException ex)
                    {
                        AdapterRequest.this.exception(ex);
                    }
                });
        }

        void
        response(Ice.ObjectPrx prx)
        {
            _amdCB.ice_response(prx);
        }

        void
        exception(Exception ex)
        {
            _locator.invoke(_locatorPrx, this); // Retry with new locator proxy.
        }

        private final String _adapterId;
        private final Ice.AMD_Locator_findAdapterById _amdCB;
    };

    public
    DiscoveryPluginI(Ice.Communicator communicator)
    {
        _communicator = communicator;
    }

    public void
    initialize()
    {
        Ice.Properties properties = _communicator.getProperties();

        boolean ipv4 = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
        String address;
        if(ipv4)
        {
            address = properties.getPropertyWithDefault("IceGridDiscovery.Address", "239.255.0.1");
        }
        else
        {
            address = properties.getPropertyWithDefault("IceGridDiscovery.Address", "ff15::1");
        }
        int port = properties.getPropertyAsIntWithDefault("IceGridDiscovery.Port", 4061);
        String intf = properties.getProperty("IceGridDiscovery.Interface");

        if(properties.getProperty("IceGridDiscovery.Reply.Endpoints").isEmpty())
        {
            StringBuilder s = new StringBuilder();
            s.append("udp");
            if(!intf.isEmpty())
            {
                s.append(" -h \"").append(intf).append("\"");
            }
            properties.setProperty("IceGridDiscovery.Reply.Endpoints", s.toString());
        }
        if(properties.getProperty("IceGridDiscovery.Locator.Endpoints").isEmpty())
        {
            properties.setProperty("IceGridDiscovery.Locator.AdapterId", java.util.UUID.randomUUID().toString());
        }

        _replyAdapter = _communicator.createObjectAdapter("IceGridDiscovery.Reply");
        _locatorAdapter = _communicator.createObjectAdapter("IceGridDiscovery.Locator");

        // We don't want those adapters to be registered with the locator so clear their locator.
        _replyAdapter.setLocator(null);
        _locatorAdapter.setLocator(null);

        String lookupEndpoints = properties.getProperty("IceGridDiscovery.Lookup");
        if(lookupEndpoints.isEmpty())
        {
            StringBuilder s = new StringBuilder();
            s.append("udp -h \"").append(address).append("\" -p ").append(port);
            if(!intf.isEmpty())
            {
                s.append(" --interface \"").append(intf).append("\"");
            }
            lookupEndpoints = s.toString();
        }

        Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceGridDiscovery/Lookup -d:" + lookupEndpoints);
        lookupPrx = lookupPrx.ice_collocationOptimized(false); // No collocation optimization for the multicast proxy!
        try
        {
            lookupPrx.ice_getConnection(); // Ensure we can establish a connection to the multicast proxy
        }
        catch(Ice.LocalException ex)
        {
            StringBuilder s = new StringBuilder();
            s.append("unable to establish multicast connection, IceGrid discovery will be disabled:\n");
            s.append("proxy = ").append(lookupPrx.toString()).append("\n");
            throw new Ice.PluginInitializationException(s.toString());
        }

        LocatorI locator = new LocatorI(LookupPrxHelper.uncheckedCast(lookupPrx), properties);
        _communicator.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(locator)));

        Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(locator)).ice_datagram();
        locator.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

        _replyAdapter.activate();
        _locatorAdapter.activate();
    }

    public void
    destroy()
    {
        _replyAdapter.destroy();
        _locatorAdapter.destroy();
    }

    private Ice.Communicator _communicator;
    private Ice.ObjectAdapter _locatorAdapter;
    private Ice.ObjectAdapter _replyAdapter;
}