1 package iotruntime.master;
4 import iotruntime.slave.IoTAddress;
5 import iotruntime.slave.IoTDeviceAddress;
6 import iotruntime.messages.*;
9 import org.objectweb.asm.ClassReader;
10 import org.objectweb.asm.ClassWriter;
11 import org.objectweb.asm.ClassVisitor;
16 import java.io.BufferedReader;
17 import java.io.InputStream;
18 import java.io.InputStreamReader;
20 import java.io.FileInputStream;
21 import java.io.FileOutputStream;
22 import java.io.OutputStream;
23 import java.io.ObjectInputStream;
24 import java.io.ObjectOutputStream;
25 import java.io.IOException;
26 import java.lang.ClassNotFoundException;
27 import java.lang.Class;
28 import java.lang.reflect.*;
29 import java.net.Socket;
30 import java.net.ServerSocket;
31 import java.nio.ByteBuffer;
33 import static java.lang.Math.toIntExact;
35 /** Class IoTMaster is responsible to use ClassRuntimeInstrumenterMaster
36 * to instrument the controller/device bytecode and starts multiple
37 * IoTSlave running on different JVM's in a distributed fashion.
39 * @author Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
43 public final class IoTMaster {
46 * IoTMaster class properties
48 * CommunicationHandler maintains the data structure for hostnames and ports
49 * LoadBalancer assigns a job onto a host based on certain metrics
51 private CommunicationHandler commHan;
52 private LoadBalancer lbIoT;
53 private RouterConfig routerConfig;
54 private ProcessJailConfig processJailConfig;
55 private ObjectInitHandler objInitHand;
56 private ObjectAddressInitHandler objAddInitHand;
57 private String[] strObjectNames;
58 // Now this can be either ClassRuntimeInstrumenterMaster or CRuntimeInstrumenterMaster
59 private Map<String,Object> mapClassNameToCrim;
62 * These properties hold information of a certain object
65 private String strObjName;
66 private String strObjClassName;
67 private String strObjClassInterfaceName;
68 private String strObjStubClsIntfaceName;
69 private String strIoTMasterHostAdd;
70 private String strIoTSlaveControllerHostAdd;
71 private String strIoTSlaveObjectHostAdd;
72 private Class[] arrFieldClasses;
73 private Object[] arrFieldValues;
74 private Socket filesocket;
77 * For connection with C++ IoTSlave
79 private ServerSocket serverSocketCpp;
80 private Socket socketCpp;
81 private BufferedInputStream inputCpp;
82 private BufferedOutputStream outputCpp;
84 // Constants that are to be extracted from config file
85 private static String STR_MASTER_MAC_ADD;
86 private static String STR_IOT_CODE_PATH;
87 private static String STR_CONT_PATH;
88 private static String STR_RUNTIME_DIR;
89 private static String STR_SLAVE_DIR;
90 private static String STR_CLS_PATH;
91 private static String STR_RMI_PATH;
92 private static String STR_RMI_HOSTNAME;
93 private static String STR_LOG_FILE_PATH;
94 private static String STR_USERNAME;
95 private static String STR_ROUTER_ADD;
96 private static String STR_MONITORING_HOST;
97 private static String STR_ZB_GATEWAY_ADDRESS;
98 private static String STR_ZB_GATEWAY_PORT;
99 private static String STR_ZB_IOTMASTER_PORT;
100 private static String STR_JVM_INIT_HEAP_SIZE;
101 private static String STR_JVM_MAX_HEAP_SIZE;
102 private static String STR_LANGUAGE_CONTROLLER;
103 private static String STR_SKEL_CLASS_SUFFIX;
104 private static String STR_STUB_CLASS_SUFFIX;
105 private static String STR_ACTIVATE_SANDBOXING;
106 private static boolean BOOL_VERBOSE;
109 * IoTMaster class constants
111 * Name constants - not to be configured by users
113 private static final String STR_IOT_MASTER_NAME = "IoTMaster";
114 private static final String STR_CFG_FILE_EXT = ".config";
115 private static final String STR_CLS_FILE_EXT = ".class";
116 private static final String STR_JAR_FILE_EXT = ".jar";
117 private static final String STR_MAC_POLICY_EXT = ".tomoyo.pol";
118 private static final String STR_SHELL_FILE_EXT = ".sh";
119 private static final String STR_SO_FILE_EXT = ".so";
120 private static final String STR_ZIP_FILE_EXT = ".zip";
121 private static final String STR_TCP_PROTOCOL = "tcp";
122 private static final String STR_UDP_PROTOCOL = "udp";
123 private static final String STR_TCPGW_PROTOCOL = "tcpgw";
124 private static final String STR_NO_PROTOCOL = "nopro";
125 private static final String STR_SELF_MAC_ADD = "00:00:00:00:00:00";
126 private static final String STR_INTERFACE_CLS_CFG = "INTERFACE_CLASS";
127 private static final String STR_INT_STUB_CLS_CFG = "INTERFACE_STUB_CLASS";
128 private static final String STR_FILE_TRF_CFG = "ADDITIONAL_ZIP_FILE";
129 private static final String STR_LANGUAGE = "LANGUAGE";
130 private static final String STR_YES = "Yes";
131 private static final String STR_NO = "No";
132 private static final String STR_JAVA = "Java";
133 private static final String STR_CPP = "C++";
134 private static final String STR_SSH = "ssh";
135 private static final String STR_SCP = "scp";
136 private static final String STR_IOTSLAVE_CPP = "./IoTSlave.o";
137 private static final String STR_SHELL_HEADER = "#!/bin/sh";
138 private static final String STR_JAVA_PATH = "/usr/bin/java";
139 private static final String STR_MAC_POL_PATH = "tomoyo/";
141 private static int INT_SIZE = 4; // send length in the size of integer (4 bytes)
142 private static final int INT_DNS_PORT = 53;
145 * Runtime class name constants - not to be configured by users
147 private static final String STR_REL_INSTRUMENTER_CLS = "iotruntime.master.RelationInstrumenter";
148 private static final String STR_SET_INSTRUMENTER_CLS = "iotruntime.master.SetInstrumenter";
149 private static final String STR_IOT_SLAVE_CLS = "iotruntime.slave.IoTSlave";
150 private static final String STR_IOT_DEV_ADD_CLS = "IoTDeviceAddress";
151 private static final String STR_IOT_ZB_ADD_CLS = "IoTZigbeeAddress";
152 private static final String STR_IOT_ADD_CLS = "IoTAddress";
158 public IoTMaster(String[] argObjNms) {
163 processJailConfig = null;
165 objAddInitHand = null;
166 strObjectNames = argObjNms;
168 strObjClassName = null;
169 strObjClassInterfaceName = null;
170 strObjStubClsIntfaceName = null;
171 strIoTMasterHostAdd = null;
172 strIoTSlaveControllerHostAdd = null;
173 strIoTSlaveObjectHostAdd = null;
174 arrFieldClasses = null;
175 arrFieldValues = null;
177 mapClassNameToCrim = null;
178 // Connection with C++ IoTSlave
179 serverSocketCpp = null;
184 STR_MASTER_MAC_ADD = null;
185 STR_IOT_CODE_PATH = null;
186 STR_CONT_PATH = null;
187 STR_RUNTIME_DIR = null;
188 STR_SLAVE_DIR = null;
191 STR_RMI_HOSTNAME = null;
192 STR_LOG_FILE_PATH = null;
194 STR_ROUTER_ADD = null;
195 STR_MONITORING_HOST = null;
196 STR_ZB_GATEWAY_ADDRESS = null;
197 STR_ZB_GATEWAY_PORT = null;
198 STR_ZB_IOTMASTER_PORT = null;
199 STR_JVM_INIT_HEAP_SIZE = null;
200 STR_JVM_MAX_HEAP_SIZE = null;
201 STR_LANGUAGE_CONTROLLER = null;
202 STR_ACTIVATE_SANDBOXING = null;
203 BOOL_VERBOSE = false;
207 * A method to initialize CommunicationHandler, LoadBalancer, RouterConfig and ObjectInitHandler
211 private void initLiveDataStructure() {
213 commHan = new CommunicationHandler(BOOL_VERBOSE);
214 lbIoT = new LoadBalancer(BOOL_VERBOSE);
215 lbIoT.setupLoadBalancer();
216 routerConfig = new RouterConfig();
217 routerConfig.getAddressList(STR_ROUTER_ADD);
218 processJailConfig = new ProcessJailConfig();
219 //processJailConfig.setAddressListObject(routerConfig.getAddressListObject());
220 objInitHand = new ObjectInitHandler(BOOL_VERBOSE);
221 objAddInitHand = new ObjectAddressInitHandler(BOOL_VERBOSE);
222 mapClassNameToCrim = new HashMap<String,Object>();
226 * getPrintWriter() gets a new PrintWriter for a new object
228 * @param strObjectName String object name
229 * @return PrintWriter
231 private PrintWriter getPrintWriter(String strObjectName) {
233 FileWriter fw = null;
235 fw = new FileWriter(strObjectName);
236 } catch (IOException ex) {
237 ex.printStackTrace();
239 PrintWriter printWriter = new PrintWriter(new BufferedWriter(fw));
244 * A method to initialize constants from config file
248 private void parseIoTMasterConfigFile() {
249 // Parse configuration file
250 Properties prop = new Properties();
251 String strCfgFileName = STR_IOT_MASTER_NAME + STR_CFG_FILE_EXT;
252 File file = new File(strCfgFileName);
253 FileInputStream fis = null;
255 fis = new FileInputStream(file);
258 } catch (IOException ex) {
259 System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
260 ex.printStackTrace();
262 // Initialize constants from config file
263 STR_MASTER_MAC_ADD = prop.getProperty("MAC_ADDRESS");
264 STR_IOT_CODE_PATH = prop.getProperty("IOT_CODE_PATH");
265 STR_CONT_PATH = prop.getProperty("CONTROLLERS_CODE_PATH");
266 STR_RUNTIME_DIR = prop.getProperty("RUNTIME_DIR");
267 STR_SLAVE_DIR = prop.getProperty("SLAVE_DIR");
268 STR_CLS_PATH = prop.getProperty("CLASS_PATH");
269 STR_RMI_PATH = prop.getProperty("RMI_PATH");
270 STR_RMI_HOSTNAME = prop.getProperty("RMI_HOSTNAME");
271 STR_LOG_FILE_PATH = prop.getProperty("LOG_FILE_PATH");
272 STR_USERNAME = prop.getProperty("USERNAME");
273 STR_ROUTER_ADD = prop.getProperty("ROUTER_ADD");
274 STR_MONITORING_HOST = prop.getProperty("MONITORING_HOST");
275 STR_ZB_GATEWAY_ADDRESS = prop.getProperty("ZIGBEE_GATEWAY_ADDRESS");
276 STR_ZB_GATEWAY_PORT = prop.getProperty("ZIGBEE_GATEWAY_PORT");
277 STR_ZB_IOTMASTER_PORT = prop.getProperty("ZIGBEE_IOTMASTER_PORT");
278 STR_JVM_INIT_HEAP_SIZE = prop.getProperty("JVM_INIT_HEAP_SIZE");
279 STR_JVM_MAX_HEAP_SIZE = prop.getProperty("JVM_MAX_HEAP_SIZE");
280 STR_SKEL_CLASS_SUFFIX = prop.getProperty("SKEL_CLASS_SUFFIX");
281 STR_STUB_CLASS_SUFFIX = prop.getProperty("STUB_CLASS_SUFFIX");
282 STR_ACTIVATE_SANDBOXING = prop.getProperty("ACTIVATE_SANDBOXING");
283 if(prop.getProperty("VERBOSE").equals(STR_YES)) {
287 RuntimeOutput.print("IoTMaster: Extracting information from config file: " + strCfgFileName, BOOL_VERBOSE);
288 RuntimeOutput.print("STR_MASTER_MAC_ADD=" + STR_MASTER_MAC_ADD, BOOL_VERBOSE);
289 RuntimeOutput.print("STR_IOT_CODE_PATH=" + STR_IOT_CODE_PATH, BOOL_VERBOSE);
290 RuntimeOutput.print("STR_CONT_PATH=" + STR_CONT_PATH, BOOL_VERBOSE);
291 RuntimeOutput.print("STR_RUNTIME_DIR=" + STR_RUNTIME_DIR, BOOL_VERBOSE);
292 RuntimeOutput.print("STR_SLAVE_DIR=" + STR_SLAVE_DIR, BOOL_VERBOSE);
293 RuntimeOutput.print("STR_CLS_PATH=" + STR_CLS_PATH, BOOL_VERBOSE);
294 RuntimeOutput.print("STR_RMI_PATH=" + STR_RMI_PATH, BOOL_VERBOSE);
295 RuntimeOutput.print("STR_RMI_HOSTNAME=" + STR_RMI_HOSTNAME, BOOL_VERBOSE);
296 RuntimeOutput.print("STR_LOG_FILE_PATH=" + STR_LOG_FILE_PATH, BOOL_VERBOSE);
297 RuntimeOutput.print("STR_USERNAME=" + STR_USERNAME, BOOL_VERBOSE);
298 RuntimeOutput.print("STR_ROUTER_ADD=" + STR_ROUTER_ADD, BOOL_VERBOSE);
299 RuntimeOutput.print("STR_MONITORING_HOST=" + STR_MONITORING_HOST, BOOL_VERBOSE);
300 RuntimeOutput.print("STR_ZB_GATEWAY_ADDRESS=" + STR_ZB_GATEWAY_ADDRESS, BOOL_VERBOSE);
301 RuntimeOutput.print("STR_ZB_GATEWAY_PORT=" + STR_ZB_GATEWAY_PORT, BOOL_VERBOSE);
302 RuntimeOutput.print("STR_ZB_IOTMASTER_PORT=" + STR_ZB_IOTMASTER_PORT, BOOL_VERBOSE);
303 RuntimeOutput.print("STR_JVM_INIT_HEAP_SIZE=" + STR_JVM_INIT_HEAP_SIZE, BOOL_VERBOSE);
304 RuntimeOutput.print("STR_JVM_MAX_HEAP_SIZE=" + STR_JVM_MAX_HEAP_SIZE, BOOL_VERBOSE);
305 RuntimeOutput.print("STR_SKEL_CLASS_SUFFIX=" + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
306 RuntimeOutput.print("STR_STUB_CLASS_SUFFIX=" + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
307 RuntimeOutput.print("STR_ACTIVATE_SANDBOXING=" + STR_ACTIVATE_SANDBOXING, BOOL_VERBOSE);
308 RuntimeOutput.print("BOOL_VERBOSE=" + BOOL_VERBOSE, BOOL_VERBOSE);
309 RuntimeOutput.print("IoTMaster: Information extracted successfully!", BOOL_VERBOSE);
313 * A method to parse information from a config file
315 * @param strCfgFileName Config file name
316 * @param strCfgField Config file field name
319 private String parseConfigFile(String strCfgFileName, String strCfgField) {
320 // Parse configuration file
321 Properties prop = new Properties();
322 File file = new File(strCfgFileName);
323 FileInputStream fis = null;
325 fis = new FileInputStream(file);
328 } catch (IOException ex) {
329 System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
330 ex.printStackTrace();
332 System.out.println("IoTMaster: Reading " + strCfgField +
333 " from config file: " + strCfgFileName + " with value: " +
334 prop.getProperty(strCfgField, null));
335 // NULL is returned if the property isn't found
336 return prop.getProperty(strCfgField, null);
340 * A method to send files from IoTMaster
342 * @param filesocket File socket object
343 * @param sFileName File name
344 * @param lFLength File length
347 private void sendFile(Socket filesocket, String sFileName, long lFLength) throws IOException {
349 File file = new File(sFileName);
350 byte[] bytFile = new byte[toIntExact(lFLength)];
351 InputStream inFileStream = new FileInputStream(file);
353 OutputStream outFileStream = filesocket.getOutputStream();
355 while ((iCount = inFileStream.read(bytFile)) > 0) {
356 outFileStream.write(bytFile, 0, iCount);
359 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
363 * A method to create a thread
365 * @param sSSHCmd SSH command
368 private void createThread(String sSSHCmd) throws IOException {
370 // Start a new thread to start a new JVM
372 Runtime runtime = Runtime.getRuntime();
373 Process process = runtime.exec(sSSHCmd);
375 RuntimeOutput.print("Executing: " + sSSHCmd, BOOL_VERBOSE);
379 * A method to send command from master and receive reply from slave
381 * @params msgSend Message object
382 * @params strPurpose String that prints purpose message
383 * @params inStream Input stream
384 * @params outStream Output stream
387 private void commMasterToSlave(Message msgSend, String strPurpose,
388 InputStream _inStream, OutputStream _outStream)
389 throws IOException, ClassNotFoundException {
391 // Send message/command from master
392 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
393 outStream.writeObject(msgSend);
394 RuntimeOutput.print("IoTMaster: Send message: " + strPurpose, BOOL_VERBOSE);
396 // Get reply from slave as acknowledgment
397 ObjectInputStream inStream = (ObjectInputStream) _inStream;
398 Message msgReply = (Message) inStream.readObject();
399 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
403 * A private method to instrument IoTSet device
405 * @params strFieldIdentifier String field name + object ID
406 * @params strFieldName String field name
407 * @params strIoTSlaveObjectHostAdd String slave host address
408 * @params inStream ObjectInputStream communication
409 * @params inStream ObjectOutputStream communication
410 * @params strLanguage String language
413 private void instrumentIoTSetDevice(String strFieldIdentifier, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
414 InputStream inStream, OutputStream outStream, String strLanguage)
415 throws IOException, ClassNotFoundException, InterruptedException {
417 // Get information from the set
418 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
419 RuntimeOutput.print("IoTMaster: DEBUG: Getting into instrumentIoTSetDevice!", BOOL_VERBOSE);
420 // Create a new IoTSet
421 if(strLanguage.equals(STR_JAVA)) {
422 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
423 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTDeviceAddress!", inStream, outStream);
425 createNewIoTSetCpp(strFieldName, outStream, inStream);
426 int iRows = listObject.size();
427 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
428 // Transfer the address
429 for(int iRow=0; iRow<iRows; iRow++) {
430 arrFieldValues = listObject.get(iRow);
431 // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
432 String strDeviceAddress = null;
433 String strDeviceAddressKey = null;
434 if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
435 strDeviceAddress = strIoTSlaveObjectHostAdd;
436 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
438 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
439 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
441 int iDestDeviceDriverPort = (int) arrFieldValues[1];
442 String strProtocol = (String) arrFieldValues[2];
443 // Check for wildcard feature
444 boolean bSrcPortWildCard = false;
445 boolean bDstPortWildCard = false;
446 if (arrFieldValues.length > 3) {
447 bSrcPortWildCard = (boolean) arrFieldValues[3];
448 bDstPortWildCard = (boolean) arrFieldValues[4];
450 // Add the port connection into communication handler - if it's not assigned yet
451 if (commHan.getComPort(strDeviceAddressKey) == null) {
452 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
456 System.out.println("\n\n DEBUG: InstrumentSetDevice: Object Name: " + strObjName);
457 System.out.println("DEBUG: InstrumentSetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
458 System.out.println("DEBUG: InstrumentSetDevice: Device address: " + strDeviceAddressKey + "\n\n");
460 // Send address one by one
461 if(strLanguage.equals(STR_JAVA)) {
462 Message msgGetIoTSetObj = null;
463 if (bDstPortWildCard) {
464 String strUniqueDev = strDeviceAddressKey + ":" + iRow;
465 msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
466 strDeviceAddress, commHan.getAdditionalPort(strUniqueDev), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
468 msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
469 strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
470 commMasterToSlave(msgGetIoTSetObj, "Get IoTSet objects!", inStream, outStream);
472 getDeviceIoTSetObjectCpp(outStream, inStream, strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort,
473 bSrcPortWildCard, bDstPortWildCard);
475 // Reinitialize IoTSet on device object
476 if(strLanguage.equals(STR_JAVA))
477 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
479 reinitializeIoTSetFieldCpp(outStream, inStream);
484 * A private method to instrument IoTSet Zigbee device
486 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
487 * @params strFieldName String field name
488 * @params strIoTSlaveObjectHostAdd String slave host address
489 * @params inStream ObjectInputStream communication
490 * @params inStream ObjectOutputStream communication
491 * @params strLanguage String language
494 private void instrumentIoTSetZBDevice(Map.Entry<String,Object> map, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
495 InputStream inStream, OutputStream outStream, String strLanguage)
496 throws IOException, ClassNotFoundException, InterruptedException {
498 // Get information from the set
499 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
500 // Create a new IoTSet
501 if(strLanguage.equals(STR_JAVA)) {
502 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
503 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTZigbeeAddress!", inStream, outStream);
504 } else // TODO: will need to implement IoTSet Zigbee for C++ later
506 // Prepare ZigbeeConfig
507 String strZigbeeGWAddress = routerConfig.getIPFromMACAddress(STR_ZB_GATEWAY_ADDRESS);
508 String strZigbeeGWAddressKey = strObjName + "-" + strZigbeeGWAddress;
509 int iZigbeeGWPort = Integer.parseInt(STR_ZB_GATEWAY_PORT);
510 int iZigbeeIoTMasterPort = Integer.parseInt(STR_ZB_IOTMASTER_PORT);
511 commHan.addDevicePort(iZigbeeIoTMasterPort);
512 ZigbeeConfig zbConfig = new ZigbeeConfig(strZigbeeGWAddress, iZigbeeGWPort, iZigbeeIoTMasterPort,
514 // Add the port connection into communication handler - if it's not assigned yet
515 if (commHan.getComPort(strZigbeeGWAddressKey) == null) {
516 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strZigbeeGWAddressKey);
518 int iRows = setInstrumenter.numberOfRows();
519 RuntimeOutput.print("IoTMaster: Number of rows for IoTZigbeeAddress: " + iRows, BOOL_VERBOSE);
522 System.out.println("\n\nDEBUG: InstrumentZigbeeDevice: Object Name: " + strObjName);
523 System.out.println("DEBUG: InstrumentZigbeeDevice: Port number: " + commHan.getComPort(strZigbeeGWAddressKey));
524 System.out.println("DEBUG: InstrumentZigbeeDevice: Device address: " + strZigbeeGWAddress + "\n\n");
526 // Transfer the address
527 for(int iRow=0; iRow<iRows; iRow++) {
528 arrFieldValues = setInstrumenter.fieldValues(iRow);
529 // Get device address
530 String strZBDevAddress = (String) arrFieldValues[0];
531 // Send policy to Zigbee gateway - TODO: Need to clear policy first?
532 zbConfig.setPolicy(strIoTSlaveObjectHostAdd, commHan.getComPort(strZigbeeGWAddressKey), strZBDevAddress);
533 // Send address one by one
534 if(strLanguage.equals(STR_JAVA)) {
535 Message msgGetIoTSetZBObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ZB_DEV_IOTSET_OBJECT, strZBDevAddress);
536 commMasterToSlave(msgGetIoTSetZBObj, "Get IoTSet objects!", inStream, outStream);
537 } else // TODO: Implement IoTSet Zigbee for C++
540 zbConfig.closeConnection();
541 // Reinitialize IoTSet on device object
542 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
547 * A private method to instrument IoTSet of addresses
549 * @params strFieldIdentifier String field name + object ID
550 * @params strFieldName String field name
551 * @params inStream ObjectInputStream communication
552 * @params inStream ObjectOutputStream communication
553 * @params strLanguage String language
556 private void instrumentIoTSetAddress(String strFieldIdentifier, String strFieldName,
557 InputStream inStream, OutputStream outStream, String strLanguage)
558 throws IOException, ClassNotFoundException, InterruptedException {
560 // Get information from the set
561 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
562 // Create a new IoTSet
563 if(strLanguage.equals(STR_JAVA)) {
564 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
565 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTAddress!", inStream, outStream);
568 int iRows = listObject.size();
569 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
570 // Transfer the address
571 for(int iRow=0; iRow<iRows; iRow++) {
572 arrFieldValues = listObject.get(iRow);
573 // Get device address
574 String strAddress = (String) arrFieldValues[0];
575 // Send address one by one
576 if(strLanguage.equals(STR_JAVA)) {
577 Message msgGetIoTSetAddObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ADD_IOTSET_OBJECT, strAddress);
578 commMasterToSlave(msgGetIoTSetAddObj, "Get IoTSet objects!", inStream, outStream);
579 } else // TODO: Implement IoTSet Address for C++
582 // Reinitialize IoTSet on device object
583 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD),
584 "Reinitialize IoTSet fields!", inStream, outStream);
589 * A private method to instrument an object on a specific machine and setting up policies
591 * @params strFieldObjectID String field object ID
592 * @params strObjControllerName String object controller name
593 * @params strLanguage String language
596 private void instrumentObject(String strFieldObjectID, String strObjControllerName, String strLanguage) throws IOException {
598 // Extract the interface name for RMI
599 // e.g. ProximitySensorInterface, TempSensorInterface, etc.
601 String strObjCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
602 strObjClassInterfaceName = parseConfigFile(strObjCfgFile, STR_INTERFACE_CLS_CFG);
603 strObjStubClsIntfaceName = parseConfigFile(strObjCfgFile, STR_INT_STUB_CLS_CFG);
604 // Create an object name, e.g. ProximitySensorImplPS1
605 strObjName = strObjClassName + strFieldObjectID;
606 // Check first if host exists
607 if(commHan.objectExists(strObjName)) {
608 // If this object exists already ...
609 // Re-read IoTSlave object hostname for further reference
610 strIoTSlaveObjectHostAdd = commHan.getHostAddress(strObjName);
611 RuntimeOutput.print("IoTMaster: Object with name: " + strObjName + " has existed!", BOOL_VERBOSE);
613 // If this is a new object ... then create one
614 // Get host address for IoTSlave from LoadBalancer
615 //strIoTSlaveObjectHostAdd = lbIoT.selectHost();
616 strIoTSlaveObjectHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
617 if (strIoTSlaveControllerHostAdd == null)
618 throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
619 RuntimeOutput.print("IoTMaster: Object name: " + strObjName, BOOL_VERBOSE);
620 // Add port connection and get port numbers
621 // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
622 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strObjName);
623 commHan.addActiveControllerObject(strFieldObjectID, strObjName, strObjClassName, strObjClassInterfaceName,
624 strObjStubClsIntfaceName, strIoTSlaveObjectHostAdd, arrFieldValues, arrFieldClasses);
625 // ROUTING POLICY: IoTMaster and device/controller object
626 // Master-slave communication
627 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
628 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
629 // ROUTING POLICY: Send the same routing policy to both the hosts
630 routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
631 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
632 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTMasterHostAdd,
633 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
634 // Need to accommodate callback functions here - open ports for TCP
635 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd,
636 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
637 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd,
638 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
639 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd,
640 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
641 // Configure MAC policies for objects
642 //String strFileName = STR_MAC_POL_PATH + strObjClassName + STR_MAC_POLICY_EXT;
643 String strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
644 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
645 processJailConfig.configureProcessJailDeviceDriverPolicies(strIoTSlaveObjectHostAdd, strObjName, strObjClassName,
646 strFileName, strIoTMasterHostAdd, commHan.getComPort(strObjName), commHan.getRMIRegPort(strObjName),
647 commHan.getRMIStubPort(strObjName));
648 processJailConfig.configureProcessJailContRMIPolicies(strObjControllerName, strIoTSlaveObjectHostAdd,
649 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
651 // Instrument the IoTSet declarations inside the class file
652 instrumentObjectIoTSet(strFieldObjectID, strLanguage);
654 // Send routing policy to router for controller object
655 // ROUTING POLICY: RMI communication - RMI registry and stub ports
656 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
657 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
658 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
659 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
660 // Send the same set of routing policies to compute nodes
661 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
662 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
663 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
664 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
665 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
666 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
667 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
668 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
673 * A private method to set router policies for IoTDeviceAddress objects
675 * @params strFieldIdentifier String field name + object ID
676 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
677 * @params strIoTSlaveObjectHostAdd String slave host address
680 private void setRouterPolicyIoTSetDevice(String strFieldIdentifier, Map.Entry<String,Object> map,
681 String strIoTSlaveObjectHostAdd) {
683 // Get information from the set
684 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
685 int iRows = setInstrumenter.numberOfRows();
686 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
687 // Transfer the address
688 for(int iRow=0; iRow<iRows; iRow++) {
689 arrFieldValues = setInstrumenter.fieldValues(iRow);
690 objAddInitHand.addField(strFieldIdentifier, arrFieldValues); // Save this for object instantiation
691 // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
692 String strDeviceAddress = null;
693 String strDeviceAddressKey = null;
694 if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
695 strDeviceAddress = strIoTSlaveObjectHostAdd;
696 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
697 } else { // Concatenate object name and IP address to give unique key - for a case where there is one device for multiple drivers
698 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
699 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
701 int iDestDeviceDriverPort = (int) arrFieldValues[1];
702 String strProtocol = (String) arrFieldValues[2];
703 // Add the port connection into communication handler - if it's not assigned yet
704 if (commHan.getComPort(strDeviceAddressKey) == null)
705 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
706 boolean bDstPortWildCard = false;
707 // Recognize this and allocate different ports for it
708 if (arrFieldValues.length > 3) {
709 bDstPortWildCard = (boolean) arrFieldValues[4];
710 if (bDstPortWildCard) { // This needs a unique source port
711 String strUniqueDev = strDeviceAddressKey + ":" + iRow;
712 commHan.addAdditionalPort(strUniqueDev);
717 System.out.println("\n\n DEBUG: InstrumentPolicySetDevice: Object Name: " + strObjName);
718 System.out.println("DEBUG: InstrumentPolicySetDevice: Port number: " + commHan.getComPort(strDeviceAddressKey));
719 System.out.println("DEBUG: InstrumentPolicySetDevice: Device address: " + strDeviceAddressKey + "\n\n");
721 // Send routing policy to router for device drivers and devices
722 // ROUTING POLICY: RMI communication - RMI registry and stub ports
723 if((iDestDeviceDriverPort == -1) && (!strProtocol.equals(STR_NO_PROTOCOL))) {
724 // Port number -1 means that we don't set the policy strictly to port number level
725 // "nopro" = no protocol specified for just TCP or just UDP (can be both used as well)
726 // ROUTING POLICY: Device driver and device
727 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
728 // ROUTING POLICY: Send to the compute node where the device driver is
729 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
730 } else if((iDestDeviceDriverPort == -1) && (strProtocol.equals(STR_NO_PROTOCOL))) {
731 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
732 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
733 } else if(strProtocol.equals(STR_TCPGW_PROTOCOL)) {
734 // This is a TCP protocol that connects, e.g. a phone to our runtime system
735 // that provides a gateway access (accessed through destination port number)
736 commHan.addDevicePort(iDestDeviceDriverPort);
737 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
738 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
739 routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
740 routerConfig.configureHostHTTPPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
741 // Configure MAC policies
742 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
743 processJailConfig.configureProcessJailGWDevicePolicies(strIoTSlaveObjectHostAdd, STR_ROUTER_ADD, strDeviceAddress, INT_DNS_PORT);
745 // Other port numbers...
746 commHan.addDevicePort(iDestDeviceDriverPort);
747 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol,
748 commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
749 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol,
750 commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
751 // Configure MAC policies
752 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
753 processJailConfig.configureProcessJailDevicePolicies(strIoTSlaveObjectHostAdd, strProtocol,
754 commHan.getComPort(strDeviceAddressKey), strDeviceAddress, iDestDeviceDriverPort);
760 * A private method to set router policies for IoTAddress objects
762 * @params strFieldIdentifier String field name + object ID
763 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
764 * @params strHostAddress String host address
767 private void setRouterPolicyIoTSetAddress(String strFieldIdentifier, Map.Entry<String,Object> map,
768 String strHostAddress, String strControllerName) {
770 // Get information from the set
771 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
772 int iRows = setInstrumenter.numberOfRows();
773 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
774 // Transfer the address
775 for(int iRow=0; iRow<iRows; iRow++) {
776 arrFieldValues = setInstrumenter.fieldValues(iRow);
777 objAddInitHand.addField(strFieldIdentifier, arrFieldValues); // Save this for object instantiation
778 // Get device address
779 String strAddress = (String) arrFieldValues[0];
780 // Setting up router policies for HTTP/HTTPs
781 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
782 if (strControllerName != null) {
783 processJailConfig.configureProcessJailInetAddressPolicies(strControllerName, STR_ROUTER_ADD, strAddress);
785 processJailConfig.configureProcessJailInetAddressPolicies(strHostAddress, STR_ROUTER_ADD, strAddress);
788 routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strHostAddress, strAddress);
789 routerConfig.configureHostHTTPPolicies(strHostAddress, strHostAddress, strAddress);
794 * A private method to instrument an object's IoTSet and IoTRelation field to up policies
796 * Mostly the IoTSet fields would contain IoTDeviceAddress objects
798 * @params strFieldObjectID String field object ID
799 * @params strLanguage String language
802 private void instrumentObjectIoTSet(String strFieldObjectID, String strLanguage) throws IOException {
804 // If this is a new object ... then create one
805 // Instrument the class source code and look for IoTSet for device addresses
806 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
807 HashMap<String,Object> hmObjectFieldObjects = null;
808 if(strLanguage.equals(STR_JAVA)) {
809 String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CLS_FILE_EXT;
810 FileInputStream fis = new FileInputStream(strObjectClassNamePath);
811 ClassReader cr = new ClassReader(fis);
812 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
813 // We need Object ID to instrument IoTDeviceAddress
814 ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, strFieldObjectID, BOOL_VERBOSE);
817 mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
818 hmObjectFieldObjects = crim.getFieldObjects();
820 String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
821 CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strObjectClassNamePath, strFieldObjectID, BOOL_VERBOSE);
822 mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
823 hmObjectFieldObjects = crim.getFieldObjects();
825 // Get the object and the class names
826 // Build objects for IoTSet and IoTRelation fields in the device object classes
827 RuntimeOutput.print("IoTMaster: Going to instrument for " + strObjClassName + " with objectID " +
828 strFieldObjectID, BOOL_VERBOSE);
829 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
830 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
831 // Iterate over HashMap and choose between processing
832 String strFieldName = map.getKey();
833 String strClassName = map.getValue().getClass().getName();
834 String strFieldIdentifier = strFieldName + strFieldObjectID;
835 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
836 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
837 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
838 // Instrument the normal IoTDeviceAddress
839 setRouterPolicyIoTSetDevice(strFieldIdentifier, map, strIoTSlaveObjectHostAdd);
840 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
841 // Instrument the IoTAddress
842 setRouterPolicyIoTSetAddress(strFieldIdentifier, map, strIoTSlaveObjectHostAdd, null);
843 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
844 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
845 RuntimeOutput.print("IoTMaster: IoTZigbeeAddress found! No router policy is set here..",
848 String strErrMsg = "IoTMaster: Device driver object" +
849 " can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
850 " or IoTSet<IoTZigbeeAddress>!";
851 throw new Error(strErrMsg);
854 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
855 throw new Error(strErrMsg);
862 * A private method to send files to a Java slave driver
864 * @params serverSocket ServerSocket
865 * @params _inStream InputStream
866 * @params _outStream OutputStream
867 * @params strObjName String
868 * @params strObjClassName String
869 * @params strObjClassInterfaceName String
870 * @params strObjStubClsIntfaceName String
871 * @params strIoTSlaveObjectHostAdd String
872 * @params strFieldObjectID String
873 * @params arrFieldValues Object[]
874 * @params arrFieldClasses Class[]
877 private void sendFileToJavaSlaveDriver(ServerSocket serverSocket, InputStream _inStream, OutputStream _outStream,
878 String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
879 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses)
880 throws IOException, ClassNotFoundException {
882 ObjectInputStream inStream = (ObjectInputStream) _inStream;
883 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
884 // Create message to transfer file first
885 String sFileName = strObjClassName + STR_JAR_FILE_EXT;
886 String sPath = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
887 File file = new File(sPath);
888 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, sFileName, file.length()),
889 "Sending file!", inStream, outStream);
890 // Send file - JAR file for object creation
891 sendFile(serverSocket.accept(), sPath, file.length());
892 Message msgReply = (Message) inStream.readObject();
893 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
894 // Pack object information to create object on a IoTSlave
895 Message msgObjIoTSlave = new MessageCreateObject(IoTCommCode.CREATE_OBJECT, strIoTSlaveObjectHostAdd,
896 strObjClassName, strObjName, strObjClassInterfaceName, strObjStubClsIntfaceName, commHan.getRMIRegPort(strObjName),
897 commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses);
899 commMasterToSlave(msgObjIoTSlave, "Sending object information", inStream, outStream);
904 * A private method to send files to a Java slave driver
908 private void sendFileToCppSlaveDriver(String strObjClassName, String strIoTSlaveObjectHostAdd)
909 throws IOException, ClassNotFoundException {
911 // Create message to transfer file first
912 String sFileName = strObjClassName + STR_ZIP_FILE_EXT;
913 String sFile = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
914 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_SLAVE_DIR;
915 runCommand(strCmdSend);
916 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
918 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " +
919 STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
920 runCommand(strCmdUnzip);
921 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
927 * Construct command line for Java IoTSlave
931 private String getCmdJavaDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
933 // Create an Shell executable
934 String strJavaCommand = STR_SHELL_HEADER + "\nexec " + STR_JAVA_PATH + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " +
935 STR_RMI_HOSTNAME + strIoTSlaveObjectHostAdd + " " + STR_IOT_SLAVE_CLS + " " + strIoTMasterHostAdd + " " +
936 commHan.getComPort(strObjName) + " " + commHan.getRMIRegPort(strObjName) + " " +
937 commHan.getRMIStubPort(strObjName) + " > " + STR_LOG_FILE_PATH + strObjName + ".log &";
938 String shellFile = "./" + strObjName + STR_SHELL_FILE_EXT;
939 createWrapperShellScript(strJavaCommand, shellFile);
940 // Send the file to the compute node
941 String strCmdSend = "scp " + shellFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_RUNTIME_DIR;
942 runCommand(strCmdSend);
943 System.out.println("IoTMaster: Sending shell file: " + strCmdSend);
944 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
949 * Construct command line for C++ IoTSlave
953 private String getCmdCppDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
955 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " +
956 STR_SLAVE_DIR + " sudo " + STR_IOTSLAVE_CPP + " " + strIoTMasterHostAdd + " " +
957 commHan.getComPort(strObjName) + " " + strObjName;
962 * createWrapperShellScript() gets a wrapper shell script
964 * @param strCommand String command
965 * @param strObjectName String object name
966 * @return PrintWriter
968 private void createWrapperShellScript(String strCommand, String strFileName) {
970 PrintWriter printWriter = getPrintWriter(strFileName);
971 printWriter.println(strCommand);
973 runCommand("chmod 755 " + strFileName);
978 * A private method to create an object on a specific machine
980 * @params strObjName String object name
981 * @params strObjClassName String object class name
982 * @params strObjClassInterfaceName String object class interface name
983 * @params strIoTSlaveObjectHostAdd String IoTSlave host address
984 * @params strFieldObjectID String field object ID
985 * @params arrFieldValues Array of field values
986 * @params arrFieldClasses Array of field classes
989 private void createObject(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
990 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses)
991 throws IOException, FileNotFoundException, ClassNotFoundException, InterruptedException {
994 String sCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
995 String strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE + "_" + strObjName);
996 if(strLanguageDriver == null) // Read just the field LANGUAGE if the first read is null
997 strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE);
998 if(strLanguageDriver == null) // Check nullness for the second time - report if it is still null
999 throw new Error("IoTMaster: Language specification missing in config file: " + sCfgFile);
1004 start = System.currentTimeMillis();
1006 // Construct ssh command line
1007 // e.g. ssh rtrimana@dw-2.eecs.uci.edu cd <path>;
1008 // java -cp $CLASSPATH:./*.jar
1009 // -Djava.rmi.server.codebase=file:./*.jar
1010 // iotruntime.IoTSlave dw-1.eecs.uci.edu 46151 23829 42874 &
1011 // The In-Port for IoTMaster is the Out-Port for IoTSlave and vice versa
1012 String strSSHCommand = null;
1013 if(strLanguageDriver.equals(STR_JAVA))
1014 strSSHCommand = getCmdJavaDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1015 else if(strLanguageDriver.equals(STR_CPP))
1016 strSSHCommand = getCmdCppDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1018 throw new Error("IoTMaster: Language specification not recognized: " + strLanguageDriver);
1019 RuntimeOutput.print("IoTMaster: Language for " + strObjName + " is " + strLanguageDriver, BOOL_VERBOSE);
1021 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
1022 // Start a new thread to start a new JVM
1023 createThread(strSSHCommand);
1024 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjName));
1025 Socket socket = serverSocket.accept();
1026 //InputStream inStream = new ObjectInputStream(socket.getInputStream());
1027 //OutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
1028 InputStream inStream = null;
1029 OutputStream outStream = null;
1030 if(strLanguageDriver.equals(STR_JAVA)) {
1031 inStream = new ObjectInputStream(socket.getInputStream());
1032 outStream = new ObjectOutputStream(socket.getOutputStream());
1033 } else { // At this point the language is certainly C++, otherwise would've complained above
1034 inStream = new BufferedInputStream(socket.getInputStream());
1035 outStream = new BufferedOutputStream(socket.getOutputStream());
1040 result = System.currentTimeMillis()-start;
1041 System.out.println("\n\n ==> Time needed to start JVM for " + strObjName + ": " + result + "\n\n");
1044 start = System.currentTimeMillis();
1046 if(strLanguageDriver.equals(STR_JAVA)) {
1047 sendFileToJavaSlaveDriver(serverSocket, inStream, outStream, strObjName,
1048 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
1049 strIoTSlaveObjectHostAdd, strFieldObjectID, arrFieldValues, arrFieldClasses);
1051 sendFileToCppSlaveDriver(strObjClassName, strIoTSlaveObjectHostAdd);
1052 createObjectCpp(strObjName, strObjClassName, strObjClassInterfaceName, strIoTSlaveObjectHostAdd,
1053 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses,
1054 outStream, inStream);
1058 result = System.currentTimeMillis()-start;
1059 System.out.println("\n\n ==> Time needed to send JAR file for " + strObjName + ": " + result + "\n\n");
1062 start = System.currentTimeMillis();
1064 // Instrument the class source code and look for IoTSet for device addresses
1065 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
1066 RuntimeOutput.print("IoTMaster: Instantiating for " + strObjClassName + " with objectID " + strFieldObjectID, BOOL_VERBOSE);
1067 // Get the object and the class names
1068 // Build objects for IoTSet and IoTRelation fields in the device object classes
1069 Object crimObj = mapClassNameToCrim.get(strObjClassName + strFieldObjectID);
1070 HashMap<String,Object> hmObjectFieldObjects = null;
1071 if (crimObj instanceof ClassRuntimeInstrumenterMaster) {
1072 ClassRuntimeInstrumenterMaster crim = (ClassRuntimeInstrumenterMaster) crimObj;
1073 hmObjectFieldObjects = crim.getFieldObjects();
1074 } else if (crimObj instanceof CRuntimeInstrumenterMaster) {
1075 CRuntimeInstrumenterMaster crim = (CRuntimeInstrumenterMaster) crimObj;
1076 hmObjectFieldObjects = crim.getFieldObjects();
1078 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
1079 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
1080 // Iterate over HashMap and choose between processing
1081 String strFieldName = map.getKey();
1082 String strClassName = map.getValue().getClass().getName();
1083 String strFieldIdentifier = strFieldName + strFieldObjectID;
1084 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
1085 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
1086 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
1087 // Instrument the normal IoTDeviceAddress
1088 synchronized(this) {
1089 //RuntimeOutput.print("IoTMaster: DEBUG: Processing " + STR_IOT_DEV_ADD_CLS + "!", BOOL_VERBOSE);
1090 instrumentIoTSetDevice(strFieldIdentifier, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1092 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
1093 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
1094 synchronized(this) {
1095 instrumentIoTSetZBDevice(map, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1097 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
1098 // Instrument the IoTAddress
1099 synchronized(this) {
1100 instrumentIoTSetAddress(strFieldIdentifier, strFieldName, inStream, outStream, strLanguageDriver);
1103 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
1104 " or IoTSet<IoTZigbeeAddress>!";
1105 throw new Error(strErrMsg);
1108 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
1109 throw new Error(strErrMsg);
1113 // TODO: Change this later
1114 if(strLanguageDriver.equals(STR_JAVA)) {
1115 ObjectOutputStream oStream = (ObjectOutputStream) outStream;
1116 oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
1117 } else { // C++ side for now will be running continuously because it's an infinite loop (not in a separate thread)
1118 createDriverObjectCpp(outStream, inStream);
1119 //endSessionCpp(outStream);
1123 result = System.currentTimeMillis()-start;
1124 System.out.println("\n\n ==> Time needed to create object " + strObjName + " and instrument IoTDeviceAddress: " + result + "\n\n");
1130 serverSocket.close();
1135 * A private method to create controller objects
1139 private void createDriverObjects() throws InterruptedException {
1141 // Create a list of threads
1142 List<Thread> threads = new ArrayList<Thread>();
1143 // Get the list of active controller objects and loop it
1144 List<String> listActiveControllerObject = commHan.getActiveControllerObjectList();
1145 for(String strObjName : listActiveControllerObject) {
1147 ObjectCreationInfo objCrtInfo = commHan.getObjectCreationInfo(strObjName);
1148 Thread objectThread = new Thread(new Runnable() {
1150 synchronized(this) {
1152 createObject(strObjName, objCrtInfo.getObjectClassName(), objCrtInfo.getObjectClassInterfaceName(),
1153 objCrtInfo.getObjectStubClassInterfaceName(), objCrtInfo.getIoTSlaveObjectHostAdd(),
1154 commHan.getFieldObjectID(strObjName), commHan.getArrayFieldValues(strObjName),
1155 commHan.getArrayFieldClasses(strObjName));
1156 } catch (IOException |
1157 ClassNotFoundException |
1158 InterruptedException ex) {
1159 ex.printStackTrace();
1164 threads.add(objectThread);
1165 objectThread.start();
1168 for (Thread thread : threads) {
1171 } catch (InterruptedException ex) {
1172 ex.printStackTrace();
1179 * A private method to instrument IoTSet
1181 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
1182 * @params strFieldName String field name
1183 * @params strLanguage String language
1186 private void instrumentIoTSet(Map.Entry<String,Object> map, String strFieldName, String strObjControllerName, String strLanguage)
1187 throws IOException, ClassNotFoundException, InterruptedException {
1189 // Get information from the set
1190 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
1191 objInitHand.addField(strFieldName, IoTCommCode.CREATE_NEW_IOTSET);
1193 int iRows = setInstrumenter.numberOfRows();
1194 for(int iRow=0; iRow<iRows; iRow++) {
1195 // Get field classes and values
1196 arrFieldClasses = setInstrumenter.fieldClasses(iRow);
1197 arrFieldValues = setInstrumenter.fieldValues(iRow);
1198 // Get object ID and class name
1199 String strObjID = setInstrumenter.fieldObjectID(iRow);
1200 strObjClassName = setInstrumenter.fieldEntryType(strObjID);
1201 // Call the method to create an object
1202 instrumentObject(strObjID, strObjControllerName, strLanguage);
1203 objInitHand.addObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1204 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName, commHan.getRMIRegPort(strObjName),
1205 commHan.getRMIStubPort(strObjName));
1211 * A private method to instrument IoTRelation
1213 * @params Map.Entry<String,Object> Entry of map IoTRelation instrumentation
1214 * @params strFieldName String field name
1215 * @params strLanguage String language
1218 private void instrumentIoTRelation(Map.Entry<String,Object> map, String strFieldName, String strObjControllerName, String strLanguage)
1219 throws IOException, ClassNotFoundException, InterruptedException {
1221 // Get information from the set
1222 RelationInstrumenter relationInstrumenter = (RelationInstrumenter) map.getValue();
1223 int iRows = relationInstrumenter.numberOfRows();
1224 objInitHand.addField(strFieldName, IoTCommCode.CREATE_NEW_IOTRELATION);
1226 for(int iRow=0; iRow<iRows; iRow++) {
1227 // Operate on the first set first
1228 arrFieldClasses = relationInstrumenter.firstFieldClasses(iRow);
1229 arrFieldValues = relationInstrumenter.firstFieldValues(iRow);
1230 String strObjID = relationInstrumenter.firstFieldObjectID(iRow);
1231 strObjClassName = relationInstrumenter.firstEntryFieldType(strObjID);
1232 // Call the method to create an object
1233 instrumentObject(strObjID, strObjControllerName, strLanguage);
1234 // Get the first object controller host address
1235 String strFirstIoTSlaveObjectHostAdd = strIoTSlaveObjectHostAdd;
1236 objInitHand.addObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1237 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
1238 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
1239 // Operate on the second set
1240 arrFieldClasses = relationInstrumenter.secondFieldClasses(iRow);
1241 arrFieldValues = relationInstrumenter.secondFieldValues(iRow);
1242 strObjID = relationInstrumenter.secondFieldObjectID(iRow);
1243 strObjClassName = relationInstrumenter.secondEntryFieldType(strObjID);
1244 // Call the method to create an object
1245 instrumentObject(strObjID, strObjControllerName, strLanguage);
1246 // Get the second object controller host address
1247 String strSecondIoTSlaveObjectHostAdd = strIoTSlaveObjectHostAdd;
1248 objInitHand.addSecondObjectIntoField(strFieldName, strIoTSlaveObjectHostAdd, strObjName,
1249 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
1250 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
1251 // ROUTING POLICY: first and second controller objects in IoTRelation
1252 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strFirstIoTSlaveObjectHostAdd,
1253 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1254 // ROUTING POLICY: Send the same routing policy to both the hosts
1255 routerConfig.configureHostMainPolicies(strFirstIoTSlaveObjectHostAdd, strFirstIoTSlaveObjectHostAdd,
1256 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1257 routerConfig.configureHostMainPolicies(strSecondIoTSlaveObjectHostAdd, strFirstIoTSlaveObjectHostAdd,
1258 strSecondIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
1263 * A method to reinitialize IoTSet and IoTRelation in the code based on ObjectInitHandler information
1265 * @params inStream ObjectInputStream communication
1266 * @params outStream ObjectOutputStream communication
1269 private void initializeSetsAndRelationsJava(InputStream inStream, OutputStream outStream)
1270 throws IOException, ClassNotFoundException {
1271 // Get list of fields
1272 List<String> strFields = objInitHand.getListOfFields();
1273 // Iterate on HostAddress
1274 for(String str : strFields) {
1275 IoTCommCode iotcommMsg = objInitHand.getFieldMessage(str);
1276 if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTSET) {
1277 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTSET
1278 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, str);
1279 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet!", inStream, outStream);
1280 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1281 for (ObjectInitInfo objInitInfo : listObject) {
1282 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTSET
1283 commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTSET_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(),
1284 objInitInfo.getObjectName(), objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(),
1285 objInitInfo.getObjectStubClassInterfaceName(), objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort()),
1286 "Get IoTSet object!", inStream, outStream);
1289 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTSET FIELD
1290 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD),
1291 "Renitialize IoTSet field!", inStream, outStream);
1292 } else if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTRELATION) {
1293 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTRELATION
1294 Message msgCrtIoTRel = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTRELATION, str);
1295 commMasterToSlave(msgCrtIoTRel, "Create new IoTRelation!", inStream, outStream);
1296 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1297 List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
1298 Iterator it = listSecondObject.iterator();
1299 for (ObjectInitInfo objInitInfo : listObject) {
1300 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (FIRST OBJECT)
1301 commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTRELATION_FIRST_OBJECT,
1302 objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(), objInitInfo.getObjectClassName(),
1303 objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1304 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort()),
1305 "Get IoTRelation first object!", inStream, outStream);
1306 ObjectInitInfo objSecObj = (ObjectInitInfo) it.next();
1307 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
1308 commMasterToSlave(new MessageGetObject(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT,
1309 objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(), objSecObj.getObjectClassName(),
1310 objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
1311 objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort()),
1312 "Get IoTRelation second object!", inStream, outStream);
1314 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTRELATION FIELD
1315 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTRELATION_FIELD),
1316 "Renitialize IoTRelation field!", inStream, outStream);
1322 * A method to reinitialize IoTSet and IoTRelation in the code based on ObjectInitHandler information
1324 * @params inStream ObjectInputStream communication
1325 * @params outStream ObjectOutputStream communication
1328 private void initializeSetsAndRelationsCpp(InputStream inStream, OutputStream outStream)
1329 throws IOException, ClassNotFoundException {
1330 // Get list of fields
1331 List<String> strFields = objInitHand.getListOfFields();
1332 // Iterate on HostAddress
1333 for(String str : strFields) {
1334 IoTCommCode iotcommMsg = objInitHand.getFieldMessage(str);
1335 if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTSET) {
1336 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTSET
1337 createNewIoTSetCpp(str, outStream, inStream);
1338 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1339 for (ObjectInitInfo objInitInfo : listObject) {
1340 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTSET
1341 getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTSET_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(),
1342 objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1343 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort(), outStream, inStream);
1345 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTSET FIELD
1346 reinitializeIoTSetFieldCpp(outStream, inStream);
1347 } else if (iotcommMsg == IoTCommCode.CREATE_NEW_IOTRELATION) {
1348 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO CREATE IOTRELATION
1349 // TODO: createNewIoTRelation needs to be created here!
1350 createNewIoTRelationCpp(str, outStream, inStream);
1351 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1352 List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
1353 Iterator it = listSecondObject.iterator();
1354 for (ObjectInitInfo objInitInfo : listObject) {
1355 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (FIRST OBJECT)
1356 getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_FIRST_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(),
1357 objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1358 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort(), outStream, inStream);
1359 ObjectInitInfo objSecObj = (ObjectInitInfo) it.next();
1360 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
1361 getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT, objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(),
1362 objSecObj.getObjectClassName(), objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
1363 objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort(), outStream, inStream);
1365 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTRELATION FIELD
1366 reinitializeIoTRelationFieldCpp(outStream, inStream);
1372 * A method to set router basic policies at once
1374 * @param strRouter String router name
1377 private void setRouterBasicPolicies(String strRouter) {
1379 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1380 routerConfig.initMainPolicy(strRouter);
1381 routerConfig.combineRouterPolicies(strRouter);
1382 routerConfig.configureRouterICMPPolicies(strRouter, strMonitorHost);
1383 routerConfig.configureRouterDHCPPolicies(strRouter);
1384 routerConfig.configureRouterDNSPolicies(strRouter);
1385 routerConfig.configureRouterSSHPolicies(strRouter, strMonitorHost);
1386 routerConfig.configureRejectPolicies(strRouter);
1390 * A method to set host basic policies at once
1392 * @param strHost String host name
1395 private void setHostBasicPolicies(String strHost) {
1397 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1398 routerConfig.initMainPolicy(strHost);
1399 routerConfig.combineRouterPolicies(strHost);
1400 routerConfig.configureHostDHCPPolicies(strHost);
1401 routerConfig.configureHostDNSPolicies(strHost);
1402 if (strHost.equals(strMonitorHost)) {
1403 // Check if this is the monitoring host
1404 routerConfig.configureHostICMPPolicies(strHost);
1405 routerConfig.configureHostSSHPolicies(strHost);
1407 routerConfig.configureHostICMPPolicies(strHost, strMonitorHost);
1408 routerConfig.configureHostSSHPolicies(strHost, strMonitorHost);
1410 // Apply SQL allowance policies to master host
1411 if (strHost.equals(strIoTMasterHostAdd)) {
1412 routerConfig.configureHostSQLPolicies(strHost);
1414 routerConfig.configureRejectPolicies(strHost);
1418 * A method to create a thread for policy deployment
1420 * @param strRouterAddress String router address to configure
1421 * @param setHostAddresses Set of strings for host addresses to configure
1424 private void createPolicyThreads(String strRouterAddress, Set<String> setHostAddresses) throws IOException {
1426 // Create a list of threads
1427 List<Thread> threads = new ArrayList<Thread>();
1428 // Start threads for hosts
1429 for(String strAddress : setHostAddresses) {
1430 Thread policyThread = new Thread(new Runnable() {
1432 synchronized(this) {
1433 routerConfig.sendHostPolicies(strAddress);
1437 threads.add(policyThread);
1438 policyThread.start();
1439 RuntimeOutput.print("Deploying policies for: " + strAddress, BOOL_VERBOSE);
1441 // A thread for router
1442 Thread policyThread = new Thread(new Runnable() {
1444 synchronized(this) {
1445 routerConfig.sendRouterPolicies(strRouterAddress);
1449 threads.add(policyThread);
1450 policyThread.start();
1451 RuntimeOutput.print("Deploying policies on router: " + strRouterAddress, BOOL_VERBOSE);
1453 for (Thread thread : threads) {
1456 } catch (InterruptedException ex) {
1457 ex.printStackTrace();
1463 * A method to create a thread for policy deployment
1465 * @param setHostAddresses Set of strings for host addresses to configure
1468 private void createMACPolicyThreads(Set<String> setHostAddresses) throws IOException {
1470 // Create a list of threads
1471 List<Thread> threads = new ArrayList<Thread>();
1472 // Start threads for hosts
1473 for(String strAddress : setHostAddresses) {
1474 Thread policyThread = new Thread(new Runnable() {
1476 synchronized(this) {
1477 processJailConfig.sendMACPolicies(strAddress);
1481 threads.add(policyThread);
1482 policyThread.start();
1483 RuntimeOutput.print("Deploying MAC policies for: " + strAddress, BOOL_VERBOSE);
1486 for (Thread thread : threads) {
1489 } catch (InterruptedException ex) {
1490 ex.printStackTrace();
1497 * A method to send files to Java IoTSlave
1499 * @params strObjControllerName String
1500 * @params serverSocket ServerSocket
1501 * @params inStream ObjectInputStream communication
1502 * @params outStream ObjectOutputStream communication
1505 private void sendFileToJavaSlave(String strObjControllerName, ServerSocket serverSocket,
1506 InputStream _inStream, OutputStream _outStream) throws IOException, ClassNotFoundException {
1508 ObjectInputStream inStream = (ObjectInputStream) _inStream;
1509 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
1511 String strControllerJarName = strObjControllerName + STR_JAR_FILE_EXT;
1512 String strControllerJarNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1513 strControllerJarName;
1514 File file = new File(strControllerJarNamePath);
1515 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerJarName, file.length()),
1516 "Sending file!", inStream, outStream);
1517 // Send file - Class file for object creation
1518 sendFile(serverSocket.accept(), strControllerJarNamePath, file.length());
1519 Message msgReply = (Message) inStream.readObject();
1520 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1521 // Send .zip file if additional zip file is specified
1522 String strObjCfgFile = strObjControllerName + STR_CFG_FILE_EXT;
1523 String strObjCfgFilePath = STR_CONT_PATH + strObjControllerName + "/" + strObjCfgFile;
1524 String strAdditionalFile = parseConfigFile(strObjCfgFilePath, STR_FILE_TRF_CFG);
1525 if (strAdditionalFile.equals(STR_YES)) {
1526 String strControllerCmpName = strObjControllerName + STR_ZIP_FILE_EXT;
1527 String strControllerCmpNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1528 strControllerCmpName;
1529 file = new File(strControllerCmpNamePath);
1530 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerCmpName, file.length()),
1531 "Sending file!", inStream, outStream);
1532 // Send file - Class file for object creation
1533 sendFile(serverSocket.accept(), strControllerCmpNamePath, file.length());
1534 msgReply = (Message) inStream.readObject();
1535 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1541 * A method to send files to C++ IoTSlave
1544 * TODO: Need to look into this (as of now, file transferred retains the "data" format,
1545 * hence it is unreadable from outside world
1547 private void sendFileToCppSlave(String sFilePath, String sFileName, Socket fileSocket,
1548 InputStream inStream, OutputStream outStream) throws IOException {
1550 sendCommCode(IoTCommCode.TRANSFER_FILE, outStream, inStream);
1552 sendString(sFileName, outStream); recvAck(inStream);
1553 File file = new File(sFilePath + sFileName);
1554 int iFileLen = toIntExact(file.length());
1555 RuntimeOutput.print("IoTMaster: Sending file " + sFileName + " with length " + iFileLen + " bytes...", BOOL_VERBOSE);
1557 sendInteger(iFileLen, outStream); recvAck(inStream);
1558 RuntimeOutput.print("IoTMaster: Sent file size!", BOOL_VERBOSE);
1559 byte[] bytFile = new byte[iFileLen];
1560 InputStream inFileStream = new FileInputStream(file);
1561 RuntimeOutput.print("IoTMaster: Opened file!", BOOL_VERBOSE);
1563 OutputStream outFileStream = fileSocket.getOutputStream();
1564 RuntimeOutput.print("IoTMaster: Got output stream!", BOOL_VERBOSE);
1566 while ((iCount = inFileStream.read(bytFile)) > 0) {
1567 outFileStream.write(bytFile, 0, iCount);
1569 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
1575 * A method to send files to C++ IoTSlave (now master using Process() to start
1576 * file transfer using scp)
1580 private void sendFileToCppSlave(String sFilePath, String sFileName) throws IOException {
1582 // Construct shell command to transfer file
1583 String sFile = sFilePath + sFileName;
1584 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_SLAVE_DIR;
1585 runCommand(strCmdSend);
1586 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
1588 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " +
1589 STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
1590 runCommand(strCmdUnzip);
1591 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
1596 * runCommand() method runs shell command
1598 * @param strCommand String that contains command line
1601 private void runCommand(String strCommand) {
1604 Runtime runtime = Runtime.getRuntime();
1605 Process process = runtime.exec(strCommand);
1607 } catch (IOException ex) {
1608 System.out.println("RouterConfig: IOException: " + ex.getMessage());
1609 ex.printStackTrace();
1610 } catch (InterruptedException ex) {
1611 System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
1612 ex.printStackTrace();
1618 * Construct command line for Java IoTSlave
1622 private String getCmdJavaIoTSlave(String strObjControllerName) {
1624 // Create an Shell executable
1625 String strJavaCommand = STR_SHELL_HEADER + "\nexec " + STR_JAVA_PATH + " " + STR_JVM_INIT_HEAP_SIZE + " " +
1626 STR_JVM_MAX_HEAP_SIZE + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " + STR_IOT_SLAVE_CLS + " " +
1627 strIoTMasterHostAdd + " " + commHan.getComPort(strObjControllerName) + " " +
1628 commHan.getRMIRegPort(strObjControllerName) + " " + commHan.getRMIStubPort(strObjControllerName) +
1629 " > " + STR_LOG_FILE_PATH + strObjControllerName + ".log &";
1630 String shellFile = "./" + strObjControllerName + STR_SHELL_FILE_EXT;
1631 createWrapperShellScript(strJavaCommand, shellFile);
1632 // Send the file to the compute node
1633 String strCmdSend = "scp " + shellFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_RUNTIME_DIR;
1634 runCommand(strCmdSend);
1635 System.out.println("IoTMaster: Sending main controller shell file: " + strCmdSend);
1636 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
1641 * Construct command line for C++ IoTSlave
1645 private String getCmdCppIoTSlave(String strObjControllerName) {
1647 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " +
1648 STR_SLAVE_DIR + " sudo " + STR_IOTSLAVE_CPP + " " + strIoTMasterHostAdd + " " +
1649 commHan.getComPort(strObjControllerName) + " " + strObjControllerName;
1654 * sendInteger() sends an integer in bytes
1656 public void sendInteger(int intSend, OutputStream outStream) throws IOException {
1658 BufferedOutputStream output = (BufferedOutputStream) outStream;
1659 // Transform integer into bytes
1660 ByteBuffer bb = ByteBuffer.allocate(INT_SIZE);
1662 // Send the byte array
1663 output.write(bb.array(), 0, INT_SIZE);
1669 * recvInteger() receives integer in bytes
1671 public int recvInteger(InputStream inStream) throws IOException {
1673 BufferedInputStream input = (BufferedInputStream) inStream;
1674 // Wait until input is available
1675 while(input.available() == 0);
1676 // Read integer - 4 bytes
1677 byte[] recvInt = new byte[INT_SIZE];
1678 input.read(recvInt, 0, INT_SIZE);
1679 int retVal = ByteBuffer.wrap(recvInt).getInt();
1686 * recvString() receives String in bytes
1688 public String recvString(InputStream inStream) throws IOException {
1690 BufferedInputStream input = (BufferedInputStream) inStream;
1691 int strLen = recvInteger(inStream);
1692 // Wait until input is available
1693 while(input.available() == 0);
1694 // Read String per strLen
1695 byte[] recvStr = new byte[strLen];
1696 input.read(recvStr, 0, strLen);
1697 String retVal = new String(recvStr);
1704 * sendString() sends a String in bytes
1706 public void sendString(String strSend, OutputStream outStream) throws IOException {
1708 BufferedOutputStream output = (BufferedOutputStream) outStream;
1709 // Transform String into bytes
1710 byte[] strSendBytes = strSend.getBytes();
1711 int strLen = strSend.length();
1712 // Send the string length first
1713 sendInteger(strLen, outStream);
1714 // Send the byte array
1715 output.write(strSendBytes, 0, strLen);
1721 * Convert integer to enum
1723 public IoTCommCode getCode(int intCode) throws IOException {
1725 IoTCommCode[] commCode = IoTCommCode.values();
1726 IoTCommCode retCode = commCode[intCode];
1735 public synchronized boolean recvAck(InputStream inStream) throws IOException {
1737 int intAck = recvInteger(inStream);
1738 IoTCommCode codeAck = getCode(intAck);
1739 if (codeAck == IoTCommCode.ACKNOWLEDGED)
1749 public void sendEndTransfer(OutputStream outStream) throws IOException {
1751 int endCode = IoTCommCode.END_TRANSFER.ordinal();
1752 sendInteger(endCode, outStream);
1757 * Send communication code to C++
1759 public void sendCommCode(IoTCommCode inpCommCode, OutputStream outStream, InputStream inStream) throws IOException {
1762 IoTCommCode commCode = inpCommCode;
1763 int intCode = commCode.ordinal();
1764 // TODO: delete this later
1765 System.out.println("DEBUG: Sending " + commCode + " with ordinal: " + intCode);
1766 sendInteger(intCode, outStream); recvAck(inStream);
1771 * Create a main controller object for C++
1773 public void createMainObjectCpp(String strObjControllerName, OutputStream outStream, InputStream inStream) throws IOException {
1775 sendCommCode(IoTCommCode.CREATE_MAIN_OBJECT, outStream, inStream);
1776 String strMainObjName = strObjControllerName;
1777 sendString(strMainObjName, outStream); recvAck(inStream);
1778 RuntimeOutput.print("IoTMaster: Create a main object: " + strMainObjName, BOOL_VERBOSE);
1783 * A helper function that converts Class into String
1785 * @param strDataType String MySQL data type
1788 public String getClassConverted(Class<?> cls) {
1790 if (cls == String.class) {
1792 } else if (cls == int.class) {
1801 * A helper function that converts Object into String for transfer to C++ slave
1803 * @param obj Object to be converted
1804 * @param strClassType String Java Class type
1807 public String getObjectConverted(Object obj) {
1809 if (obj instanceof String) {
1810 return (String) obj;
1811 } else if (obj instanceof Integer) {
1812 return Integer.toString((Integer) obj);
1820 * Create a driver object for C++
1822 public void createObjectCpp(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strIoTSlaveObjectHostAdd,
1823 Integer iRMIRegistryPort, Integer iRMIStubPort, Object[] arrFieldValues, Class[] arrFieldClasses,
1824 OutputStream outStream, InputStream inStream) throws IOException {
1826 sendCommCode(IoTCommCode.CREATE_OBJECT, outStream, inStream);
1827 RuntimeOutput.print("IoTMaster: Send request to create a driver object... ", BOOL_VERBOSE);
1828 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjName, BOOL_VERBOSE);
1829 sendString(strObjName, outStream); recvAck(inStream);
1830 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjClassName, BOOL_VERBOSE);
1831 sendString(strObjClassName, outStream); recvAck(inStream);
1832 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjClassInterfaceName, BOOL_VERBOSE);
1833 sendString(strObjStubClsIntfaceName, outStream); recvAck(inStream);
1834 RuntimeOutput.print("IoTMaster: Driver object skeleton class name: " + strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
1835 sendString(strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, outStream); recvAck(inStream);
1836 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1837 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1838 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1839 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1840 int numOfArgs = arrFieldValues.length;
1841 RuntimeOutput.print("IoTMaster: Send constructor arguments! Number of arguments: " + numOfArgs, BOOL_VERBOSE);
1842 sendInteger(numOfArgs, outStream); recvAck(inStream);
1843 for(Object obj : arrFieldValues) {
1844 String str = getObjectConverted(obj);
1845 sendString(str, outStream); recvAck(inStream);
1847 RuntimeOutput.print("IoTMaster: Send constructor argument classes!", BOOL_VERBOSE);
1848 for(Class cls : arrFieldClasses) {
1849 String str = getClassConverted(cls);
1850 sendString(str, outStream); recvAck(inStream);
1856 * Create new IoTSet for C++
1858 public void createNewIoTSetCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1860 sendCommCode(IoTCommCode.CREATE_NEW_IOTSET, outStream, inStream);
1861 RuntimeOutput.print("IoTMaster: Creating new IoTSet...", BOOL_VERBOSE);
1862 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1863 sendString(strObjFieldName, outStream); recvAck(inStream);
1868 * Create new IoTRelation for C++
1870 public void createNewIoTRelationCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1872 sendCommCode(IoTCommCode.CREATE_NEW_IOTRELATION, outStream, inStream);
1873 RuntimeOutput.print("IoTMaster: Creating new IoTRelation...", BOOL_VERBOSE);
1874 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1875 sendString(strObjFieldName, outStream); recvAck(inStream);
1880 * Get a IoTDeviceAddress object for C++
1882 public void getDeviceIoTSetObjectCpp(OutputStream outStream, InputStream inStream,
1883 String strDeviceAddress, int iSourcePort, int iDestPort, boolean bSourceWildCard, boolean bDestWildCard) throws IOException {
1885 sendCommCode(IoTCommCode.GET_DEVICE_IOTSET_OBJECT, outStream, inStream);
1886 RuntimeOutput.print("IoTMaster: Getting IoTDeviceAddress...", BOOL_VERBOSE);
1887 sendString(strDeviceAddress, outStream); recvAck(inStream);
1888 sendInteger(iSourcePort, outStream); recvAck(inStream);
1889 sendInteger(iDestPort, outStream); recvAck(inStream);
1890 int iSourceWildCard = (bSourceWildCard ? 1 : 0);
1891 sendInteger(iSourceWildCard, outStream); recvAck(inStream);
1892 int iDestWildCard = (bDestWildCard ? 1 : 0);
1893 sendInteger(iDestWildCard, outStream); recvAck(inStream);
1894 RuntimeOutput.print("IoTMaster: Send device address: " + strDeviceAddress, BOOL_VERBOSE);
1899 * Get a IoTSet content object for C++
1901 public void getIoTSetRelationObjectCpp(IoTCommCode iotCommCode, String strIoTSlaveHostAddress, String strObjectName, String strObjectClassName,
1902 String strObjectClassInterfaceName, String strObjectStubClassInterfaceName, int iRMIRegistryPort, int iRMIStubPort,
1903 OutputStream outStream, InputStream inStream) throws IOException {
1905 sendCommCode(iotCommCode, outStream, inStream);
1906 RuntimeOutput.print("IoTMaster: Getting IoTSet object content...", BOOL_VERBOSE);
1908 RuntimeOutput.print("IoTMaster: Send host address: " + strIoTSlaveHostAddress, BOOL_VERBOSE);
1909 sendString(strIoTSlaveHostAddress, outStream); recvAck(inStream);
1910 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjectName, BOOL_VERBOSE);
1911 sendString(strObjectName, outStream); recvAck(inStream);
1912 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjectClassName, BOOL_VERBOSE);
1913 sendString(strObjectClassName, outStream); recvAck(inStream);
1914 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjectClassInterfaceName, BOOL_VERBOSE);
1915 sendString(strObjectClassInterfaceName, outStream); recvAck(inStream);
1916 RuntimeOutput.print("IoTMaster: Driver object stub class name: " + strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
1917 sendString(strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, outStream); recvAck(inStream);
1918 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1919 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1920 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1921 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1926 * Reinitialize IoTRelation field for C++
1928 private void reinitializeIoTRelationFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1930 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTRelation field!", BOOL_VERBOSE);
1931 sendCommCode(IoTCommCode.REINITIALIZE_IOTRELATION_FIELD, outStream, inStream);
1932 RuntimeOutput.print("IoTMaster: Reinitialize IoTRelation field!", BOOL_VERBOSE);
1937 * Reinitialize IoTSet field for C++
1939 private void reinitializeIoTSetFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1941 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTSet field!", BOOL_VERBOSE);
1942 sendCommCode(IoTCommCode.REINITIALIZE_IOTSET_FIELD, outStream, inStream);
1943 RuntimeOutput.print("IoTMaster: Reinitialize IoTSet field!", BOOL_VERBOSE);
1948 * Create driver object for C++
1950 private void createDriverObjectCpp(OutputStream outStream, InputStream inStream) throws IOException {
1952 sendCommCode(IoTCommCode.CREATE_DRIVER_OBJECT, outStream, inStream);
1953 RuntimeOutput.print("IoTMaster: Send command to create driver object!", BOOL_VERBOSE);
1958 * Invoke init() for C++
1960 private void invokeInitMethodCpp(OutputStream outStream, InputStream inStream) throws IOException {
1962 sendCommCode(IoTCommCode.INVOKE_INIT_METHOD, outStream, inStream);
1963 RuntimeOutput.print("IoTMaster: Invoke init method!", BOOL_VERBOSE);
1968 * End session for C++
1970 public void endSessionCpp(OutputStream outStream) throws IOException {
1972 // Send message to end session
1973 IoTCommCode endSessionCode = IoTCommCode.END_SESSION;
1974 int intCode = endSessionCode.ordinal();
1975 sendInteger(intCode, outStream);
1976 //RuntimeOutput.print("IoTMaster: Send request to create a main object: " + strObjName, BOOL_VERBOSE);
1977 RuntimeOutput.print("IoTMaster: Send request to end session!", BOOL_VERBOSE);
1982 * A method to assign objects to multiple JVMs, including
1983 * the controller/device object that uses other objects
1984 * in IoTSet and IoTRelation
1988 private void createObjects() {
1995 // Extract hostname for this IoTMaster from MySQL DB
1996 strIoTMasterHostAdd = routerConfig.getIPFromMACAddress(STR_MASTER_MAC_ADD);
1997 // Assign a new list of PrintWriter objects
1998 routerConfig.renewPrintWriter();
1999 // Loop as we can still find controller/device classes
2000 for(int i=0; i<strObjectNames.length; i++) {
2002 start = System.currentTimeMillis();
2003 // Assign a new list of main PrintWriter objects
2004 routerConfig.renewMainPrintWriter();
2005 // Get controller names one by one
2006 String strObjControllerName = strObjectNames[i];
2007 // Use LoadBalancer to assign a host address
2008 //strIoTSlaveControllerHostAdd = lbIoT.selectHost();
2009 strIoTSlaveControllerHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
2010 if (strIoTSlaveControllerHostAdd == null)
2011 throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
2012 // == START INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2013 // Add port connection and get port numbers
2014 // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
2015 commHan.addPortConnection(strIoTSlaveControllerHostAdd, strObjControllerName);
2016 // ROUTING POLICY: IoTMaster and main controller object
2017 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
2018 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2019 // ROUTING POLICY: Send the same routing policy to both the hosts
2020 routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
2021 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2022 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTMasterHostAdd,
2023 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2025 String strControllerCfg = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2026 STR_LANGUAGE_CONTROLLER = parseConfigFile(strControllerCfg, STR_LANGUAGE);
2027 if(STR_LANGUAGE_CONTROLLER == null)
2028 throw new Error("IoTMaster: Language specification missing in config file: " + strControllerCfg);
2029 // Construct ssh command line and create a controller thread for e.g. AcmeProximity
2030 String strSSHCommand = null;
2031 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2032 strSSHCommand = getCmdJavaIoTSlave(strObjControllerName);
2033 else if(STR_LANGUAGE_CONTROLLER.equals(STR_CPP))
2034 strSSHCommand = getCmdCppIoTSlave(strObjControllerName);
2036 throw new Error("IoTMaster: Language specification not recognized: " + STR_LANGUAGE_CONTROLLER);
2037 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
2038 createThread(strSSHCommand);
2039 // Wait for connection
2040 // Create a new socket for communication
2041 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjControllerName));
2042 Socket socket = serverSocket.accept();
2043 InputStream inStream = null;
2044 OutputStream outStream = null;
2045 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2046 inStream = new ObjectInputStream(socket.getInputStream());
2047 outStream = new ObjectOutputStream(socket.getOutputStream());
2048 } else { // At this point the language is certainly C++, otherwise would've complained above
2049 inStream = new BufferedInputStream(socket.getInputStream());
2050 outStream = new BufferedOutputStream(socket.getOutputStream());
2053 RuntimeOutput.print("IoTMaster: Communication established!", BOOL_VERBOSE);
2056 result = System.currentTimeMillis()-start;
2057 System.out.println("\n\n ==> From start until after SSH for main controller: " + result);
2059 start = System.currentTimeMillis();
2061 // Send files for every controller class
2062 // e.g. AcmeProximity.jar and AcmeProximity.zip
2063 String strControllerClassName = strObjControllerName + STR_CLS_FILE_EXT;
2064 String strControllerClassNamePath = STR_CONT_PATH + strObjControllerName + "/" +
2065 strControllerClassName;
2067 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2068 sendFileToJavaSlave(strObjControllerName, serverSocket, inStream, outStream);
2069 // Create main controller/device object
2070 commMasterToSlave(new MessageCreateMainObject(IoTCommCode.CREATE_MAIN_OBJECT, strObjControllerName),
2071 "Create main object!", inStream, outStream);
2073 String strControllerZipFile = strObjControllerName + STR_ZIP_FILE_EXT;
2074 String strControllerFilePath = STR_CONT_PATH + strObjControllerName + "/";
2075 sendFileToCppSlave(strControllerFilePath, strControllerZipFile);
2076 createMainObjectCpp(strObjControllerName, outStream, inStream);
2078 // Write basic MAC policies for controller
2079 //String strFileName = STR_MAC_POL_PATH + strObjControllerName + STR_MAC_POLICY_EXT;
2080 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
2081 String strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
2082 processJailConfig.configureProcessJailControllerPolicies(strObjControllerName, strFileName,
2083 strIoTMasterHostAdd, commHan.getComPort(strObjControllerName));
2086 result = System.currentTimeMillis()-start;
2087 System.out.println("\n\n ==> From IoTSlave start until main controller object is created: " + result);
2088 System.out.println(" ==> Including file transfer times!\n\n");
2090 start = System.currentTimeMillis();
2092 // == END INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2093 // Instrumenting one file
2094 RuntimeOutput.print("IoTMaster: Opening class file: " + strControllerClassName, BOOL_VERBOSE);
2095 RuntimeOutput.print("IoTMaster: Class file path: " + strControllerClassNamePath, BOOL_VERBOSE);
2096 HashMap<String,Object> hmControllerFieldObjects = null;
2097 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2098 FileInputStream fis = new FileInputStream(strControllerClassNamePath);
2099 ClassReader cr = new ClassReader(fis);
2100 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
2101 ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, null, BOOL_VERBOSE);
2104 hmControllerFieldObjects = crim.getFieldObjects();
2106 String strControllerConfigFile = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2107 CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strControllerConfigFile, null, BOOL_VERBOSE);
2108 hmControllerFieldObjects = crim.getFieldObjects();
2110 // Get the object and the class names
2111 // Build objects for IoTSet and IoTRelation fields in the controller/device classes
2112 //HashMap<String,Object> hmControllerFieldObjects = crim.getFieldObjects();
2113 for(Map.Entry<String,Object> map : hmControllerFieldObjects.entrySet()) {
2114 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
2115 // Iterate over HashMap and choose between processing
2116 // SetInstrumenter vs. RelationInstrumenter
2117 String strFieldName = map.getKey();
2118 String strClassName = map.getValue().getClass().getName();
2120 System.out.println("\n\nDEBUG: Instrumenting IoTSet and IoTRelation objects!!!");
2121 System.out.println("DEBUG: Field name: " + strFieldName);
2122 System.out.println("DEBUG: Class name: " + strFieldName + "\n\n");
2124 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
2125 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
2126 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
2127 String strErrMsg = "IoTMaster: Controller object" +
2128 " cannot have IoTSet<IoTDeviceAddress>!";
2129 throw new Error(strErrMsg);
2130 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
2131 String strErrMsg = "IoTMaster: Controller object" +
2132 " cannot have IoTSet<ZigbeeAddress>!";
2133 throw new Error(strErrMsg);
2134 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
2135 // Instrument the IoTAddress
2136 setRouterPolicyIoTSetAddress(strFieldName, map, strIoTSlaveControllerHostAdd, strObjControllerName);
2137 instrumentIoTSetAddress(strFieldName, strFieldName, inStream, outStream, STR_LANGUAGE_CONTROLLER);
2140 instrumentIoTSet(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2142 } else if (strClassName.equals(STR_REL_INSTRUMENTER_CLS)) {
2143 instrumentIoTRelation(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2146 // Combine controller MAC policies with the main policy file for the host
2147 String strTempFileName = "./" + strObjControllerName + STR_MAC_POLICY_EXT;
2148 processJailConfig.combineControllerMACPolicies(strIoTSlaveControllerHostAdd, strObjControllerName, strTempFileName);
2149 processJailConfig.close();
2152 result = System.currentTimeMillis()-start;
2153 System.out.println("\n\n ==> Time needed to instrument device driver objects: " + result + "\n\n");
2154 System.out.println(" ==> #Objects: " + commHan.getActiveControllerObjectList().size() + "\n\n");
2157 start = System.currentTimeMillis();
2159 // ROUTING POLICY: implement basic policies to reject all other irrelevant traffics
2160 for(String s: commHan.getHosts()) {
2161 setHostBasicPolicies(s);
2163 // We retain all the basic policies for router,
2164 // but we delete the initial allowance policies for internal all TCP and UDP communications
2165 setRouterBasicPolicies(STR_ROUTER_ADD);
2166 routerConfig.closeMain();
2167 // Deploy the policy
2168 HashSet<String> setAddresses = new HashSet<String>(commHan.getHosts());
2169 setAddresses.add(strIoTMasterHostAdd);
2170 createPolicyThreads(STR_ROUTER_ADD, setAddresses);
2173 result = System.currentTimeMillis()-start;
2174 System.out.println("\n\n ==> Time needed to send policy files and deploy them : " + result + "\n\n");
2177 start = System.currentTimeMillis();
2179 // Separating object creations and Set/Relation initializations
2180 createDriverObjects();
2183 result = System.currentTimeMillis()-start;
2184 System.out.println("\n\n ==> Time needed to instantiate objects: " + result + "\n\n");
2186 start = System.currentTimeMillis();
2188 // Sets and relations initializations
2189 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2190 initializeSetsAndRelationsJava(inStream, outStream);
2192 initializeSetsAndRelationsCpp(inStream, outStream);;
2195 result = System.currentTimeMillis()-start;
2196 System.out.println("\n\n ==> Time needed to initialize sets and relations: " + result + "\n\n");
2198 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2199 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO EXECUTE INIT METHOD
2200 commMasterToSlave(new MessageSimple(IoTCommCode.INVOKE_INIT_METHOD), "Invoke init() method!", inStream, outStream);
2202 invokeInitMethodCpp(outStream, inStream);
2203 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO END PROCESS
2204 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2205 ObjectOutputStream oStream = (ObjectOutputStream) outStream;
2206 oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
2207 } else // C++ side will wait until the program finishes, it's not generating a separate thread for now
2208 //endSessionCpp(outStream);
2212 serverSocket.close();
2213 objInitHand.clearObjectInitHandler();
2214 commHan.printLists();
2215 commHan.clearCommunicationHandler();
2216 lbIoT.printHostInfo();
2217 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
2218 createMACPolicyThreads(setAddresses);
2220 // Close access to policy files and deploy policies
2221 routerConfig.close();
2223 } catch (IOException |
2224 InterruptedException |
2225 ClassNotFoundException ex) {
2226 System.out.println("IoTMaster: Exception: "
2228 ex.printStackTrace();
2232 public static void main(String args[]) {
2234 // Detect the available controller/device classes
2235 // Input args[] should be used to list the controllers/devices
2236 // e.g. java IoTMaster AcmeProximity AcmeThermostat AcmeVentController
2237 IoTMaster iotMaster = new IoTMaster(args);
2239 iotMaster.parseIoTMasterConfigFile();
2240 // Initialize CommunicationHandler, LoadBalancer, and RouterConfig
2241 iotMaster.initLiveDataStructure();
2243 iotMaster.createObjects();