aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/interpreter-rete/src/main/java/tools/refinery/interpreter/rete/network/Network.java
blob: 04fd645f6c638f960b37e5cd6c14bef0924047f8 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2004-2008 Gabor Bergmann and Daniel Varro
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-v20.html.
 *
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/

package tools.refinery.interpreter.rete.network;

import tools.refinery.interpreter.rete.boundary.InputConnector;
import tools.refinery.interpreter.rete.recipes.ReteNodeRecipe;
import tools.refinery.interpreter.matchers.tuple.Tuple;
import tools.refinery.interpreter.matchers.util.CollectionsFactory;
import tools.refinery.interpreter.matchers.util.Direction;
import tools.refinery.interpreter.rete.matcher.ReteEngine;
import tools.refinery.interpreter.rete.remote.Address;
import tools.refinery.interpreter.rete.traceability.RecipeTraceInfo;
import tools.refinery.interpreter.rete.util.Options;

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Gabor Bergmann
 *
 */
public class Network {
    final int threads;

    protected ArrayList<ReteContainer> containers;
    ReteContainer headContainer;
    private int firstContainer = 0;
    private int nextContainer = 0;

    // the following fields exist only if threads > 0
    protected final Map<ReteContainer, Long> globalTerminationCriteria;
    protected Map<ReteContainer, Long> reportedClocks = null;
    protected Lock updateLock = null; // grab during normal update operations
    protected Lock structuralChangeLock = null; // grab if the network structure
                                                // is to
    // be changed

    // Knowledge of the outside world
    private ReteEngine engine;
    protected NodeFactory nodeFactory;
    protected InputConnector inputConnector;

    // Node and recipe administration
    // incl. addresses for existing nodes by recipe (where available)
    // Maintained by NodeProvisioner of each container
    Map<ReteNodeRecipe, Address<? extends Node>> nodesByRecipe = CollectionsFactory.createMap();
    Set<RecipeTraceInfo> recipeTraces = CollectionsFactory.createSet();

    /**
     * @throws IllegalStateException
     *             if no node has been constructed for the recipe
     */
    public synchronized Address<? extends Node> getExistingNodeByRecipe(ReteNodeRecipe recipe) {
        final Address<? extends Node> node = nodesByRecipe.get(recipe);
        if (node == null)
            throw new IllegalStateException(String.format("Rete node for recipe %s not constructed yet.", recipe));
        return node;
    }

    /**
     * @return null if no node has been constructed for the recipe
     */
    public synchronized Address<? extends Node> getNodeByRecipeIfExists(ReteNodeRecipe recipe) {
        final Address<? extends Node> node = nodesByRecipe.get(recipe);
        return node;
    }

    /**
     * @param threads
     *            the number of threads to operate the network with; 0 means single-threaded operation, 1 starts an
     *            asynchronous thread to operate the RETE net, >1 uses multiple RETE containers.
     */
    public Network(int threads, ReteEngine engine) {
        super();
        this.threads = threads;
        this.engine = engine;
        this.inputConnector = new InputConnector(this);
        this.nodeFactory = new NodeFactory(engine.getLogger());

        containers = new ArrayList<ReteContainer>();
        firstContainer = (threads > 1) ? Options.firstFreeContainer : 0; // NOPMD
        nextContainer = firstContainer;

        if (threads > 0) {
            globalTerminationCriteria = CollectionsFactory.createMap();
            reportedClocks = CollectionsFactory.createMap();
            ReadWriteLock rwl = new ReentrantReadWriteLock();
            updateLock = rwl.readLock();
            structuralChangeLock = rwl.writeLock();
            for (int i = 0; i < threads; ++i)
                containers.add(new ReteContainer(this, true));
        } else {
			containers.add(new ReteContainer(this, false));
			globalTerminationCriteria = null;
		}
        headContainer = containers.get(0);
    }

    /**
     * Kills this Network along with all containers and message consumption cycles.
     */
    public void kill() {
        for (ReteContainer container : containers) {
            container.kill();
        }
        containers.clear();
    }

    /**
     * Returns the head container, that is guaranteed to reside in the same JVM as the Network object.
     */
    public ReteContainer getHeadContainer() {
        return headContainer;
    }

    /**
     * Returns the next container in round-robin fashion. Configurable not to yield head container.
     */
    public ReteContainer getNextContainer() {
        if (nextContainer >= containers.size())
            nextContainer = firstContainer;
        return containers.get(nextContainer++);
    }

    /**
     * Internal message delivery method.
     *
     * @pre threads > 0
     */
    private void sendUpdate(Address<? extends Receiver> receiver, Direction direction, Tuple updateElement) {
        ReteContainer affectedContainer = receiver.getContainer();
        synchronized (globalTerminationCriteria) {
            long newCriterion = affectedContainer.sendUpdateToLocalAddress(receiver, direction, updateElement);
            terminationCriterion(affectedContainer, newCriterion);
        }
    }

    /**
     * Internal message delivery method for single-threaded operation
     *
     * @pre threads == 0
     */
    private void sendUpdateSingleThreaded(Address<? extends Receiver> receiver, Direction direction,
            Tuple updateElement) {
        ReteContainer affectedContainer = receiver.getContainer();
        affectedContainer.sendUpdateToLocalAddressSingleThreaded(receiver, direction, updateElement);
    }

    /**
     * Internal message delivery method.
     *
     * @pre threads > 0
     */
    private void sendUpdates(Address<? extends Receiver> receiver, Direction direction,
            Collection<Tuple> updateElements) {
        if (updateElements.isEmpty())
            return;
        ReteContainer affectedContainer = receiver.getContainer();
        synchronized (globalTerminationCriteria) {
            long newCriterion = affectedContainer.sendUpdatesToLocalAddress(receiver, direction, updateElements);
            terminationCriterion(affectedContainer, newCriterion);
        }
    }

    /**
     * Sends an update message to the receiver node, indicating a newly found or lost partial matching. The node may
     * reside in any of the containers associated with this network. To be called from a user thread during normal
     * operation, NOT during construction.
     *
     * @since 2.4
     */
    public void sendExternalUpdate(Address<? extends Receiver> receiver, Direction direction, Tuple updateElement) {
        if (threads > 0) {
            try {
                updateLock.lock();
                sendUpdate(receiver, direction, updateElement);
            } finally {
                updateLock.unlock();
            }
        } else {
            sendUpdateSingleThreaded(receiver, direction, updateElement);
            // getHeadContainer().
        }
    }

    /**
     * Sends an update message to the receiver node, indicating a newly found or lost partial matching. The node may
     * reside in any of the containers associated with this network. To be called from a user thread during
     * construction.
     *
     * @pre: structuralChangeLock MUST be grabbed by the sequence (but not necessarily this thread, as the sequence may
     *       span through network calls, that's why it's not enforced here )
     *
     * @return the value of the target container's clock at the time when the message was accepted into its message
     *         queue
     * @since 2.4
     */
    public void sendConstructionUpdate(Address<? extends Receiver> receiver, Direction direction, Tuple updateElement) {
        // structuralChangeLock.lock();
        if (threads > 0)
            sendUpdate(receiver, direction, updateElement);
        else
            receiver.getContainer().sendUpdateToLocalAddressSingleThreaded(receiver, direction, updateElement);
        // structuralChangeLock.unlock();
    }

    /**
     * Sends multiple update messages atomically to the receiver node, indicating a newly found or lost partial
     * matching. The node may reside in any of the containers associated with this network. To be called from a user
     * thread during construction.
     *
     * @pre: structuralChangeLock MUST be grabbed by the sequence (but not necessarily this thread, as the sequence may
     *       span through network calls, that's why it's not enforced here )
     *
     * @since 2.4
     */
    public void sendConstructionUpdates(Address<? extends Receiver> receiver, Direction direction,
            Collection<Tuple> updateElements) {
        // structuralChangeLock.lock();
        if (threads > 0)
            sendUpdates(receiver, direction, updateElements);
        else
            receiver.getContainer().sendUpdatesToLocalAddressSingleThreaded(receiver, direction, updateElements);
        // structuralChangeLock.unlock();
    }

    /**
     * Establishes connection between a supplier and a receiver node, regardless which container they are in. Not to be
     * called remotely, because this method enforces the structural lock.
     *
     * @param supplier
     * @param receiver
     * @param synchronise
     *            indicates whether the receiver should be synchronised to the current contents of the supplier
     */
    public void connectRemoteNodes(Address<? extends Supplier> supplier, Address<? extends Receiver> receiver,
            boolean synchronise) {
        try {
            if (threads > 0)
                structuralChangeLock.lock();
            receiver.getContainer().connectRemoteNodes(supplier, receiver, synchronise);
        } finally {
            if (threads > 0)
                structuralChangeLock.unlock();
        }
    }

    /**
     * Severs connection between a supplier and a receiver node, regardless which container they are in. Not to be
     * called remotely, because this method enforces the structural lock.
     *
     * @param supplier
     * @param receiver
     * @param desynchronise
     *            indicates whether the current contents of the supplier should be subtracted from the receiver
     */
    public void disconnectRemoteNodes(Address<? extends Supplier> supplier, Address<? extends Receiver> receiver,
            boolean desynchronise) {
        try {
            if (threads > 0)
                structuralChangeLock.lock();
            receiver.getContainer().disconnectRemoteNodes(supplier, receiver, desynchronise);
        } finally {
            if (threads > 0)
                structuralChangeLock.unlock();
        }
    }

    /**
     * Containers use this method to report whenever they run out of messages in their queue.
     *
     * To be called from the thread of the reporting container.
     *
     * @pre threads > 0.
     * @param reportingContainer
     *            the container reporting the emptiness of its message queue.
     * @param clock
     *            the value of the container's clock when reporting.
     * @param localTerminationCriteria
     *            the latest clock values this container has received from other containers since the last time it
     *            reported termination.
     */
    void reportLocalUpdateTermination(ReteContainer reportingContainer, long clock,
            Map<ReteContainer, Long> localTerminationCriteria) {
        synchronized (globalTerminationCriteria) {
            for (Entry<ReteContainer, Long> criterion : localTerminationCriteria.entrySet()) {
                terminationCriterion(criterion.getKey(), criterion.getValue());
            }

            reportedClocks.put(reportingContainer, clock);
            Long criterion = globalTerminationCriteria.get(reportingContainer);
            if (criterion != null && criterion < clock)
                globalTerminationCriteria.remove(reportingContainer);

            if (globalTerminationCriteria.isEmpty())
                globalTerminationCriteria.notifyAll();
        }
    }

    /**
     * @pre threads > 0
     */
    private void terminationCriterion(ReteContainer affectedContainer, long newCriterion) {
        synchronized (globalTerminationCriteria) {
            Long oldCriterion = globalTerminationCriteria.get(affectedContainer);
            Long oldClock = reportedClocks.get(affectedContainer);
            long relevantClock = oldClock == null ? 0 : oldClock;
            if ((relevantClock <= newCriterion) && (oldCriterion == null || oldCriterion < newCriterion)) {
                globalTerminationCriteria.put(affectedContainer, newCriterion);
            }
        }
    }

    /**
     * Waits until all rete update operations are settled in all containers. Returns immediately, if no updates are
     * pending.
     *
     * To be called from any user thread.
     */
    public void waitForReteTermination() {
        if (threads > 0) {
            synchronized (globalTerminationCriteria) {
                while (!globalTerminationCriteria.isEmpty()) {
                    try {
                        globalTerminationCriteria.wait();
                    } catch (InterruptedException e) {
						Thread.currentThread().interrupt();
                    }
                }
            }
        } else
            headContainer.deliverMessagesSingleThreaded();
    }

    /**
     * Waits to execute action until all rete update operations are settled in all containers. Runs action and returns
     * immediately, if no updates are pending. The given action is guaranteed to be run when the terminated state still
     * persists.
     *
     * @param action
     *            the action to be run when reaching the steady-state.
     *
     *            To be called from any user thread.
     */
    public void waitForReteTermination(Runnable action) {
        if (threads > 0) {
            synchronized (globalTerminationCriteria) {
                while (!globalTerminationCriteria.isEmpty()) {
                    try {
                        globalTerminationCriteria.wait();
                    } catch (InterruptedException e) {
						Thread.currentThread().interrupt();
                    }
                }
                action.run();
            }
        } else {
            headContainer.deliverMessagesSingleThreaded();
            action.run();
        }

    }

    /**
     * @return an unmodifiable set of known recipe traces
     */
    public Set<RecipeTraceInfo> getRecipeTraces() {
        return Collections.unmodifiableSet(recipeTraces);
    }

    /**
     * @return an unmodifiable list of containers
     */
    public List<ReteContainer> getContainers() {
        return Collections.unmodifiableList(containers);
    }

    public Lock getStructuralChangeLock() {
        return structuralChangeLock;
    }

    public NodeFactory getNodeFactory() {
        return nodeFactory;
    }

    public InputConnector getInputConnector() {
        return inputConnector;
    }

    public ReteEngine getEngine() {
        return engine;
    }

}