summaryrefslogtreecommitdiffstats
path: root/sca-java-1.x/tags/1.0.1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/SCANodeImpl.java
blob: de33e8db1f3a4a93d122f5e9be1baeb5f62bd1c4 (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
 /*
 * 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.tuscany.sca.node.impl;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.namespace.QName;

import org.apache.tuscany.sca.assembly.AssemblyFactory;
import org.apache.tuscany.sca.assembly.Component;
import org.apache.tuscany.sca.assembly.Composite;
import org.apache.tuscany.sca.assembly.xml.Constants;
import org.apache.tuscany.sca.contribution.Contribution;
import org.apache.tuscany.sca.contribution.DeployedArtifact;
import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint;
import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
import org.apache.tuscany.sca.contribution.resolver.impl.ModelResolverImpl;
import org.apache.tuscany.sca.contribution.service.ContributionService;
import org.apache.tuscany.sca.core.ExtensionPointRegistry;
import org.apache.tuscany.sca.core.assembly.ActivationException;
import org.apache.tuscany.sca.domain.SCADomain;
import org.apache.tuscany.sca.host.embedded.impl.ReallySmallRuntime;
import org.apache.tuscany.sca.node.NodeException;
import org.apache.tuscany.sca.node.NodeFactoryImpl;
import org.apache.tuscany.sca.node.SCADomainFinder;
import org.apache.tuscany.sca.node.SCANode;

/**
 * A local representation of the sca domain running on a single node
 * 
 * @version $Rev: 552343 $ $Date: 2007-09-09 23:54:46 +0100 (Sun, 09 Sep 2007) $
 */
public class SCANodeImpl implements SCANode {
	
    private final static Logger logger = Logger.getLogger(SCANodeImpl.class.getName());
	     
    // class loader used to get application resources
    private ClassLoader nodeClassLoader;    
    
    // identity and endpoints for the node and the domain it belongs to
    private String nodeURI;
    private URL nodeURL;
    private String domainURI; 
    private URL domainURL;
    private String nodeGroupURI;

    // The tuscany runtime that does the hard work
    private ReallySmallRuntime nodeRuntime;
    
    // the top level components in this node. A subset of the the domain level composite
    private Composite nodeComposite; 
    
    // the domain that the node belongs to. This object acts as a proxy to the domain
    private SCADomain scaDomain;
    
    // collection for managing contributions that have been added to the node 
    private Map<String, Contribution> contributions = new HashMap<String, Contribution>();    
    private Map<QName, Composite> composites = new HashMap<QName, Composite>();
    private List<QName> compositesToStart = new ArrayList<QName>();
       
    // methods defined on the implementation only
       
    /** 
     * Creates a node connected to a wider domain.  To find its place in the domain 
     * node and domain identifiers must be provided. 
     * 
     * @param domainUri - identifies what host and port the domain service is running on, e.g. http://localhost:8081
     * @param nodeUri - if this is a url it is assumed that this will be used as root url for management components, e.g. http://localhost:8082
     * @param nodeGroupURI the uri of the node group. This is the enpoint URI of the head of the
     * group of nodes. For example, in load balancing scenarios this will be the loaded balancer itself 
     * @throws ActivationException
     */
    public SCANodeImpl(String nodeURI, String domainURI, String nodeGroupURI) throws NodeException {
        this.domainURI = domainURI;
        this.nodeURI = nodeURI;
        this.nodeGroupURI = nodeGroupURI;
        this.nodeClassLoader = Thread.currentThread().getContextClassLoader();        
        init();
    }    
    
    /** 
     * Creates a node connected to a wider domain and allows a classpath to be specified.  
     * To find its place in the domain node and domain identifiers must be provided. 
     * 
     * @param domainUri - identifies what host and port the domain service is running on, e.g. http://localhost:8081
     * @param nodeUri - if this is a url it is assumed that this will be used as root url for management components, e.g. http://localhost:8082
     * @param nodeGroupURI the uri of the node group. This is the enpoint URI of the head of the
     * group of nodes. For example, in load balancing scenarios this will be the loaded balancer itself 
     * @param cl - the ClassLoader to use for loading system resources for the node
     * @throws ActivationException
     */
    public SCANodeImpl(String nodeURI, String domainURI, String nodeGroupURI, ClassLoader cl) throws NodeException {
        this.domainURI = domainURI;
        this.nodeURI = nodeURI;
        this.nodeGroupURI = nodeGroupURI;
        this.nodeClassLoader = cl;
        init();
    }    
    
    /**
     * Work out if we are representing a domain in memory or can go out to the network to 
     * get domain information. This all depends on whether there is a management
     * composite on the classpath
     */
    private void init() throws NodeException {
        try {
            
            // create a node runtime for the domain contributions to run on
            nodeRuntime = new ReallySmallRuntime(nodeClassLoader);
            
            // Start the runtime
            nodeRuntime.start();
            
            // Create an in-memory domain level composite
            AssemblyFactory assemblyFactory = nodeRuntime.getAssemblyFactory();
            nodeComposite = assemblyFactory.createComposite();
            nodeComposite.setName(new QName(Constants.SCA10_NS, "node"));
            nodeComposite.setURI(nodeURI);
            
            // add the top level composite into the composite activator
            nodeRuntime.getCompositeActivator().setDomainComposite(nodeComposite);             
          
            // check whether node uri is an absolute url,            
            try {
                URI tmpURI = new URI(nodeURI); 
                if (tmpURI.isAbsolute()){
                    nodeURL = tmpURI.toURL();
                }
            } catch(Exception ex) {
                nodeURL = null;
            }
            
            // create a link to the domain 
            scaDomain = SCADomainFinder.newInstance().getSCADomain(domainURI);
            
            // add the node to the domain
            ((SCADomainImpl)scaDomain).addNode(this);  
            
            // If a non-null domain name is provided make the node available to the model
            // this causes the runtime to start registering binding-sca service endpoints
            // with the domain so only makes sense if we know we have a domain to talk to
            if (domainURI != null) {
                ModelFactoryExtensionPoint factories = nodeRuntime.getExtensionPointRegistry().getExtensionPoint(ModelFactoryExtensionPoint.class);
                NodeFactoryImpl nodeFactory = new NodeFactoryImpl(this);
                factories.addFactory(nodeFactory);    
            }
 
        } catch(Exception ex) {
            throw new NodeException(ex);
        }
    }
    
    // temp methods to help integrate with existing code
    
    public ReallySmallRuntime getNodeRuntime() {
        return nodeRuntime;
    }
    
    public Component getComponent(String componentName) {
        for (Composite composite: nodeComposite.getIncludes()) {
            for (Component component: composite.getComponents()) {
                if (component.getName().equals(componentName)) {
                    return component;
                }
            }
        }
        return null;
    }    
    
    public List<Component> getComponents() {
        List<Component> components = new ArrayList<Component>();
        for (Composite composite: nodeComposite.getIncludes()) {
            components.addAll(composite.getComponents());
        }
        return components;
    }    
    
    /**
     * Stating to think about how a node advertises what it can do. 
     * Maybe need to turn this round and ask the node to decide whether it
     * can process a list of artifacts
     * @return
     */
    public List<String> getFeatures() {
        List<String> featureList = new ArrayList<String>();
        
        ExtensionPointRegistry registry = nodeRuntime.getExtensionPointRegistry();
        
        // TODO - how to get registered features?
        ModelFactoryExtensionPoint factories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class);
        
        return null;
    }
    
    
    // API methods 
    
    public void start() throws NodeException {
        startComposites();
    }
    
    public void stop() throws NodeException {
        try {
            // remove contributions
            removeAllContributions();           
        } catch (Exception ex) {
            throw new NodeException(ex);
        }
    }    
 
    public String getURI(){
        return nodeURI;
    }
    
    public SCADomain getDomain(){
        return scaDomain;
    }   
    
    public void addContribution(String contributionURI, URL contributionURL) throws NodeException {
        addContribution(contributionURI, contributionURL, null);
    }
    
    public void addContribution(String contributionURI, URL contributionURL, ClassLoader contributionClassLoader ) throws NodeException {
       try {            
            if (contributionURL != null) {
                ModelResolver modelResolver = null;
                
                // if the contribution is to be resolved using a separate class loader
                // then create a new model resolver
                if (contributionClassLoader != null)  {
                    modelResolver = new ModelResolverImpl(contributionClassLoader);
                }
                
                // Add the contribution to the node
                ContributionService contributionService = nodeRuntime.getContributionService();
                Contribution contribution = contributionService.contribute(contributionURI, 
                                                                           contributionURL, 
                                                                           modelResolver, 
                                                                           false);
                
                // remember the contribution
                contributions.put(contributionURI, contribution);
                    
                // remember all the composites that have been found
                for (DeployedArtifact artifact : contribution.getArtifacts()) {
                    if (artifact.getModel() instanceof Composite) {
                        Composite composite = (Composite)artifact.getModel();
                        composites.put(composite.getName(), composite);
                    }
                }
                
                // remember all the deployable composites ready to be started
                for (Composite composite : contribution.getDeployables()) {
                    compositesToStart.add(composite.getName());
                }  
                
                
                // add the contribution to the domain. It will generally already be there
                // unless the contribution has been added to the node itself. 
                ((SCADomainImpl)scaDomain).registerContribution(nodeURI, contributionURI, contributionURL.toExternalForm());                  
                
            } else {
                    throw new ActivationException("Contribution " + contributionURL + " not found");
            }  
        } catch (Exception ex) {
            throw new NodeException(ex);
        }        
    }

    private void removeAllContributions() throws NodeException {
        try {     
            // stop any running composites
            stopComposites();
            
            // Remove all contributions
            for (String contributionURI : contributions.keySet()){
                nodeRuntime.getContributionService().remove(contributionURI);
                contributions.remove(contributionURI);
            }
        } catch (Exception ex) {
            throw new NodeException(ex);
        }   
    }
    
    public void deployComposite(QName compositeName) throws NodeException {
        // if the named composite is not already in the list then 
        // add it
        if (compositesToStart.indexOf(compositeName) == -1 ){
            compositesToStart.add(compositeName);  
        }
    }
    
    private void startComposites() throws NodeException {
        try {
            if (compositesToStart.size() == 0 ){
                logger.log(Level.INFO, nodeURI + 
                                       " has no composites to start" );
            } else {  
                for (QName compositeName : compositesToStart) {
                    Composite composite = composites.get(compositeName);
                    
                    if (composite == null) {
                        logger.log(Level.INFO, "Composite not found during start: " + compositeName);
                    } else {
                        logger.log(Level.INFO, "Starting composite: " + compositeName);
                        
                        // Add the composite to the top level domain
                        nodeComposite.getIncludes().add(composite);
                        nodeRuntime.getCompositeBuilder().build(composite); 
                        
                        // activate the composite
                        nodeRuntime.getCompositeActivator().activate(composite);              
                        
                        //start the composite
                        nodeRuntime.getCompositeActivator().start(composite);
                    }
                }
            }

        } catch (Exception ex) {
            throw new NodeException(ex);
        }  
    }    

    private void stopComposites() throws NodeException {
        
        try {
            if (compositesToStart.size() == 0 ){
                throw new NodeException("Stopping node " + 
                                        nodeURI + 
                                        " with no composite started");
            }
            for (QName compositeName : compositesToStart) {
                logger.log(Level.INFO, "Stopping composite: " + compositeName);
                
                Composite composite = composites.get(compositeName);   

                nodeRuntime.getCompositeActivator().stop(composite);
                nodeRuntime.getCompositeActivator().deactivate(composite);
                
                composites.remove(compositeName);               
            }
            
            compositesToStart.clear(); 
        } catch (NodeException ex) {
        throw ex;            
            
        } catch (Exception ex) {
            throw new NodeException(ex);
        }              

    }
      
}