summaryrefslogtreecommitdiffstats
path: root/tags/java/sca/1.5.1/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeProcessCollectionImpl.java
blob: 019c2562ec686ee2176fc48d59f0af23e787f049 (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
/*
 * 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.implementation.node.manager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import org.apache.tuscany.sca.data.collection.Entry;
import org.apache.tuscany.sca.data.collection.Item;
import org.apache.tuscany.sca.data.collection.ItemCollection;
import org.apache.tuscany.sca.data.collection.LocalItemCollection;
import org.apache.tuscany.sca.data.collection.NotFoundException;
import org.apache.tuscany.sca.node.launcher.NodeLauncher;
import org.osoa.sca.ServiceRuntimeException;
import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Scope;
import org.osoa.sca.annotations.Service;

/**
 * Implementation of a node process collection service. 
 *
 * @version $Rev$ $Date$
 */
@Scope("COMPOSITE")
@Service(interfaces={ItemCollection.class, LocalItemCollection.class})
public class NodeProcessCollectionImpl implements ItemCollection, LocalItemCollection {

    private static final Logger logger = Logger.getLogger(NodeProcessCollectionImpl.class.getName());    

    private List<SCANodeVM> nodeVMs = new ArrayList<SCANodeVM>();

    /**
     * Initialize the component.
     */
    @Init
    public void initialize() {
    }
    
    public Entry<String, Item>[] getAll() {
        logger.fine("getAll");
        
        // Return all the running VMs
        List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>();
        for (SCANodeVM vm: nodeVMs) {
            entries.add(entry(vm));
        }
        return entries.toArray(new Entry[entries.size()]);
    }

    public Item get(String key) throws NotFoundException {
        logger.fine("get " + key);

        // Return the specified VM
        SCANodeVM vm = vm(key);
        if (vm == null) {
            throw new NotFoundException();
        }
        
        return item(vm);
    }

    public String post(String key, Item item) {
        logger.fine("post " + key);

        // If the VM is already running just return it
        SCANodeVM vm = vm(key);
        if (vm != null) {
            if (vm.isAlive()) {
                return key;
            } else {
                // Remove dead VM entry
                try {
                    vm.stop();
                } catch (InterruptedException e) {
                    throw new ServiceRuntimeException(e);
                }
                nodeVMs.remove(vm);
            }
        }

        // Start a new VM and add it to the collection
        vm = new SCANodeVM(key);
        nodeVMs.add(0, vm);
        try {
            vm.start();
        } catch (IOException e) {
            throw new ServiceRuntimeException(e);
        }
        
        return key;
    }

    public void put(String key, Item item) throws NotFoundException {
        throw new UnsupportedOperationException();
    }

    public void delete(String key) throws NotFoundException {
        logger.fine("delete " + key);
        
        // Stop a VM and remove it from the collection
        SCANodeVM vm = vm(key);
        if (vm != null) {
            try {
                vm.stop();
            } catch (InterruptedException e) {
                throw new ServiceRuntimeException(e);
            }
            nodeVMs.remove(vm);
        } else {
            //throw new NotFoundException();
        }
    }
    
    public Entry<String, Item>[] query(String queryString) {
        logger.fine("query " + queryString);
        
        if (queryString.startsWith("node=")) {
            
            // Return the log for the specified VM
            String key = queryString.substring(queryString.indexOf('=') + 1);
            List<Entry<String, Item>> entries = new ArrayList<Entry<String, Item>>();
            for (SCANodeVM vm: nodeVMs) {
                if (vm.getNodeName().equals(key)) {
                    entries.add(entry(vm));
                }
            }
            return entries.toArray(new Entry[entries.size()]);
            
        } else {
            throw new UnsupportedOperationException();
        }
    }
    
    /**
     * Returns the specified VM.
     * 
     * @param key
     * @return
     */
    private SCANodeVM vm(String key) {
        for (SCANodeVM vm: nodeVMs) {
            if (key.equals(vm.getNodeName())) {
                return vm;
            }
        }
        return null;
    }

    /**
     * Returns an entry representing a VM.
     * 
     * @param vm
     * @return
     */
    private static Entry<String, Item> entry(SCANodeVM vm) {
        Entry<String, Item> entry = new Entry<String, Item>();
        entry.setKey(vm.getNodeName());
        entry.setData(item(vm));
        return entry;
    }
    
    /**
     * Returns an item representing a VM.
     * 
     * @param vm
     * @return
     */
    private static Item item(SCANodeVM vm) {
        Item item = new Item();
        String key = vm.getNodeName();
        item.setTitle(title(key));
        item.setLink("/node-config/" + vm.getNodeName());
        item.setContents("<span id=\"log\" style=\"white-space: nowrap; font-size: small\">" + vm.getLog().toString() + "</span>");
        return item;
    }
    
    /**
     * Represent a child Java VM running an SCA node.
     */
    private static class SCANodeVM {
        private String nodeName;
        private StringBuffer log;
        private Process process;
        private Thread monitor;
        private int status;
        
        SCANodeVM(String nodeName) {
            log = new StringBuffer();
            this.nodeName =nodeName;
        }
        
        /**
         * Starts a node in a new VM.
         */
        private void start() throws IOException {

            // Determine the node configuration URI
            String nodeConfigurationURI = NodeManagerUtil.nodeConfigurationURI(nodeName);
            
            // Build the Java VM command line
            Properties props = System.getProperties();
            String java = props.getProperty("java.home") + "/bin/java";
            String cp = props.getProperty("java.class.path");
            String main = NodeLauncher.class.getName();
            final List<String> command = new ArrayList<String>();
            command.add(java);
            command.add("-cp");
            command.add(cp);
            
            // Propagate TUSCANY properties
            String tuscanyHome = props.getProperty("TUSCANY_HOME");
            if (tuscanyHome != null) {
                command.add("-DTUSCANY_HOME=" + tuscanyHome);
            }
            String tuscanyPath = props.getProperty("TUSCANY_PATH");
            if (tuscanyPath != null) {
                command.add("-DTUSCANY_PATH=" + tuscanyPath);
            }

            // Specify the main class and parameters
            command.add(main);
            command.add(nodeConfigurationURI);
            
            logger.info("Starting " + "java " + main + " " + nodeConfigurationURI);
            
            // Start the VM
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            process = builder.start();
            
            logger.info("Started " + process);
            
            // Start a thread to monitor the process
            final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            monitor = new Thread(new Runnable() {
                public void run() {
                    try {
                        for (;;) {
                            String s = reader.readLine();
                            if (s != null) {
                                logger.info(s);
                                log.append(s + "<br>");
                            } else {
                                break;
                            }
                        }
                        status = process.waitFor();
                    } catch (IOException e) {
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            monitor.start();
        }

        /**
         * Returns the composite used to start this VM.
         * @return
         */
        String getNodeName() {
            return nodeName;
        }
        
        /**
         * Returns the log for this VM.
         * 
         * @return
         */
        StringBuffer getLog() {
            return log;
        }

        /**
         * Returns true if the VM is alive
         * 
         * @return
         */
        private boolean isAlive() {
            return monitor.isAlive();
        }
        
        /**
         * Returns the VM status code.
         * @return
         */
        int getStatus() {
            return status;
        }

        /**
         * Stops the VM.
         * 
         * @throws InterruptedException
         */
        private void stop() throws InterruptedException {
            logger.info("Stopping " + process);
            
            process.destroy();
            monitor.join();
            
            logger.info("Stopped " + process);
        }
    }
    
    /**
     * Returns a node title.
     * 
     * @param key
     * @return
     */
    private static String title(String key) {
        return key;
    }

}