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 String STR_POLICY_ON;
107 private static String STR_MAC_TO_IP_TRANSLATION;
108 private static boolean BOOL_VERBOSE;
111 * IoTMaster class constants
113 * Name constants - not to be configured by users
115 private static final String STR_IOT_MASTER_NAME = "IoTMaster";
116 private static final String STR_CFG_FILE_EXT = ".config";
117 private static final String STR_CLS_FILE_EXT = ".class";
118 private static final String STR_JAR_FILE_EXT = ".jar";
119 private static final String STR_MAC_POLICY_EXT = ".tomoyo.pol";
120 private static final String STR_SHELL_FILE_EXT = ".sh";
121 private static final String STR_SO_FILE_EXT = ".so";
122 private static final String STR_ZIP_FILE_EXT = ".zip";
123 private static final String STR_TCP_PROTOCOL = "tcp";
124 private static final String STR_UDP_PROTOCOL = "udp";
125 private static final String STR_TCPGW_PROTOCOL = "tcpgw";
126 private static final String STR_NO_PROTOCOL = "nopro";
127 private static final String STR_SELF_MAC_ADD = "00:00:00:00:00:00";
128 private static final String STR_INTERFACE_CLS_CFG = "INTERFACE_CLASS";
129 private static final String STR_INT_STUB_CLS_CFG = "INTERFACE_STUB_CLASS";
130 private static final String STR_FILE_TRF_CFG = "ADDITIONAL_ZIP_FILE";
131 private static final String STR_LANGUAGE = "LANGUAGE";
132 private static final String STR_ADD_MAC_POL = "ADDITIONAL_MAC_POLICY";
133 private static final String STR_YES = "Yes";
134 private static final String STR_NO = "No";
135 private static final String STR_JAVA = "Java";
136 private static final String STR_CPP = "C++";
137 private static final String STR_SSH = "ssh";
138 private static final String STR_SCP = "scp";
139 private static final String STR_IOTSLAVE_CPP = "./IoTSlave.o";
140 private static final String STR_SHELL_HEADER = "#!/bin/sh";
141 private static final String STR_JAVA_PATH = "/usr/bin/java";
142 private static final String STR_MAC_POL_PATH = "tomoyo/";
143 private static final String STR_TMP = "tmp";
144 private static final String STR_ARP = "arp";
146 private static int INT_SIZE = 4; // send length in the size of integer (4 bytes)
147 private static final int INT_DNS_PORT = 53;
150 * Runtime class name constants - not to be configured by users
152 private static final String STR_REL_INSTRUMENTER_CLS = "iotruntime.master.RelationInstrumenter";
153 private static final String STR_SET_INSTRUMENTER_CLS = "iotruntime.master.SetInstrumenter";
154 private static final String STR_IOT_SLAVE_CLS = "iotruntime.slave.IoTSlave";
155 private static final String STR_IOT_DEV_ADD_CLS = "IoTDeviceAddress";
156 private static final String STR_IOT_ZB_ADD_CLS = "IoTZigbeeAddress";
157 private static final String STR_IOT_ADD_CLS = "IoTAddress";
163 public IoTMaster(String[] argObjNms) {
168 processJailConfig = null;
170 objAddInitHand = null;
171 strObjectNames = argObjNms;
173 strObjClassName = null;
174 strObjClassInterfaceName = null;
175 strObjStubClsIntfaceName = null;
176 strIoTMasterHostAdd = null;
177 strIoTSlaveControllerHostAdd = null;
178 strIoTSlaveObjectHostAdd = null;
179 arrFieldClasses = null;
180 arrFieldValues = null;
182 mapClassNameToCrim = null;
183 // Connection with C++ IoTSlave
184 serverSocketCpp = null;
189 STR_MASTER_MAC_ADD = null;
190 STR_IOT_CODE_PATH = null;
191 STR_CONT_PATH = null;
192 STR_RUNTIME_DIR = null;
193 STR_SLAVE_DIR = null;
196 STR_RMI_HOSTNAME = null;
197 STR_LOG_FILE_PATH = null;
199 STR_ROUTER_ADD = null;
200 STR_MONITORING_HOST = null;
201 STR_ZB_GATEWAY_ADDRESS = null;
202 STR_ZB_GATEWAY_PORT = null;
203 STR_ZB_IOTMASTER_PORT = null;
204 STR_JVM_INIT_HEAP_SIZE = null;
205 STR_JVM_MAX_HEAP_SIZE = null;
206 STR_LANGUAGE_CONTROLLER = null;
207 STR_ACTIVATE_SANDBOXING = null;
208 STR_POLICY_ON = null;
209 STR_MAC_TO_IP_TRANSLATION = null;
210 BOOL_VERBOSE = false;
214 * A method to initialize CommunicationHandler, LoadBalancer, RouterConfig and ObjectInitHandler
218 private void initLiveDataStructure() {
220 commHan = new CommunicationHandler(BOOL_VERBOSE);
221 lbIoT = new LoadBalancer(BOOL_VERBOSE);
222 lbIoT.setupLoadBalancer();
223 routerConfig = new RouterConfig();
224 // Get MAC to IP translation either from /tmp/dhcp.leases or arp command
225 if (STR_MAC_TO_IP_TRANSLATION.equals(STR_TMP))
226 routerConfig.getAddressListTmp(STR_ROUTER_ADD);
227 else if (STR_MAC_TO_IP_TRANSLATION.equals(STR_ARP))
228 routerConfig.getAddressListArp(STR_ROUTER_ADD);
230 throw new Error("IoTMaster: Unknown value for STR_MAC_TO_IP_TRANSLATION: " + STR_MAC_TO_IP_TRANSLATION);
231 processJailConfig = new ProcessJailConfig();
232 objInitHand = new ObjectInitHandler(BOOL_VERBOSE);
233 objAddInitHand = new ObjectAddressInitHandler(BOOL_VERBOSE);
234 mapClassNameToCrim = new HashMap<String,Object>();
238 * getPrintWriter() gets a new PrintWriter for a new object
240 * @param strObjectName String object name
241 * @return PrintWriter
243 private PrintWriter getPrintWriter(String strObjectName) {
245 FileWriter fw = null;
247 fw = new FileWriter(strObjectName);
248 } catch (IOException ex) {
249 ex.printStackTrace();
251 PrintWriter printWriter = new PrintWriter(new BufferedWriter(fw));
256 * A method to initialize constants from config file
260 private void parseIoTMasterConfigFile() {
261 // Parse configuration file
262 Properties prop = new Properties();
263 String strCfgFileName = STR_IOT_MASTER_NAME + STR_CFG_FILE_EXT;
264 File file = new File(strCfgFileName);
265 FileInputStream fis = null;
267 fis = new FileInputStream(file);
270 } catch (IOException ex) {
271 System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
272 ex.printStackTrace();
274 // Initialize constants from config file
275 STR_MASTER_MAC_ADD = prop.getProperty("MAC_ADDRESS");
276 STR_IOT_CODE_PATH = prop.getProperty("IOT_CODE_PATH");
277 STR_CONT_PATH = prop.getProperty("CONTROLLERS_CODE_PATH");
278 STR_RUNTIME_DIR = prop.getProperty("RUNTIME_DIR");
279 STR_SLAVE_DIR = prop.getProperty("SLAVE_DIR");
280 STR_CLS_PATH = prop.getProperty("CLASS_PATH");
281 STR_RMI_PATH = prop.getProperty("RMI_PATH");
282 STR_RMI_HOSTNAME = prop.getProperty("RMI_HOSTNAME");
283 STR_LOG_FILE_PATH = prop.getProperty("LOG_FILE_PATH");
284 STR_USERNAME = prop.getProperty("USERNAME");
285 STR_ROUTER_ADD = prop.getProperty("ROUTER_ADD");
286 STR_MONITORING_HOST = prop.getProperty("MONITORING_HOST");
287 STR_ZB_GATEWAY_ADDRESS = prop.getProperty("ZIGBEE_GATEWAY_ADDRESS");
288 STR_ZB_GATEWAY_PORT = prop.getProperty("ZIGBEE_GATEWAY_PORT");
289 STR_ZB_IOTMASTER_PORT = prop.getProperty("ZIGBEE_IOTMASTER_PORT");
290 STR_JVM_INIT_HEAP_SIZE = prop.getProperty("JVM_INIT_HEAP_SIZE");
291 STR_JVM_MAX_HEAP_SIZE = prop.getProperty("JVM_MAX_HEAP_SIZE");
292 STR_SKEL_CLASS_SUFFIX = prop.getProperty("SKEL_CLASS_SUFFIX");
293 STR_STUB_CLASS_SUFFIX = prop.getProperty("STUB_CLASS_SUFFIX");
294 STR_ACTIVATE_SANDBOXING = prop.getProperty("ACTIVATE_SANDBOXING");
295 STR_POLICY_ON = prop.getProperty("POLICY_ON");
296 STR_MAC_TO_IP_TRANSLATION = prop.getProperty("MAC_TO_IP_TRANSLATION");
297 if(prop.getProperty("VERBOSE").equals(STR_YES)) {
301 RuntimeOutput.print("IoTMaster: Extracting information from config file: " + strCfgFileName, BOOL_VERBOSE);
302 RuntimeOutput.print("STR_MASTER_MAC_ADD=" + STR_MASTER_MAC_ADD, BOOL_VERBOSE);
303 RuntimeOutput.print("STR_IOT_CODE_PATH=" + STR_IOT_CODE_PATH, BOOL_VERBOSE);
304 RuntimeOutput.print("STR_CONT_PATH=" + STR_CONT_PATH, BOOL_VERBOSE);
305 RuntimeOutput.print("STR_RUNTIME_DIR=" + STR_RUNTIME_DIR, BOOL_VERBOSE);
306 RuntimeOutput.print("STR_SLAVE_DIR=" + STR_SLAVE_DIR, BOOL_VERBOSE);
307 RuntimeOutput.print("STR_CLS_PATH=" + STR_CLS_PATH, BOOL_VERBOSE);
308 RuntimeOutput.print("STR_RMI_PATH=" + STR_RMI_PATH, BOOL_VERBOSE);
309 RuntimeOutput.print("STR_RMI_HOSTNAME=" + STR_RMI_HOSTNAME, BOOL_VERBOSE);
310 RuntimeOutput.print("STR_LOG_FILE_PATH=" + STR_LOG_FILE_PATH, BOOL_VERBOSE);
311 RuntimeOutput.print("STR_USERNAME=" + STR_USERNAME, BOOL_VERBOSE);
312 RuntimeOutput.print("STR_ROUTER_ADD=" + STR_ROUTER_ADD, BOOL_VERBOSE);
313 RuntimeOutput.print("STR_MONITORING_HOST=" + STR_MONITORING_HOST, BOOL_VERBOSE);
314 RuntimeOutput.print("STR_ZB_GATEWAY_ADDRESS=" + STR_ZB_GATEWAY_ADDRESS, BOOL_VERBOSE);
315 RuntimeOutput.print("STR_ZB_GATEWAY_PORT=" + STR_ZB_GATEWAY_PORT, BOOL_VERBOSE);
316 RuntimeOutput.print("STR_ZB_IOTMASTER_PORT=" + STR_ZB_IOTMASTER_PORT, BOOL_VERBOSE);
317 RuntimeOutput.print("STR_JVM_INIT_HEAP_SIZE=" + STR_JVM_INIT_HEAP_SIZE, BOOL_VERBOSE);
318 RuntimeOutput.print("STR_JVM_MAX_HEAP_SIZE=" + STR_JVM_MAX_HEAP_SIZE, BOOL_VERBOSE);
319 RuntimeOutput.print("STR_SKEL_CLASS_SUFFIX=" + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
320 RuntimeOutput.print("STR_STUB_CLASS_SUFFIX=" + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
321 RuntimeOutput.print("STR_ACTIVATE_SANDBOXING=" + STR_ACTIVATE_SANDBOXING, BOOL_VERBOSE);
322 RuntimeOutput.print("STR_POLICY_ON=" + STR_POLICY_ON, BOOL_VERBOSE);
323 RuntimeOutput.print("STR_MAC_TO_IP_TRANSLATION=" + STR_MAC_TO_IP_TRANSLATION, BOOL_VERBOSE);
324 RuntimeOutput.print("BOOL_VERBOSE=" + BOOL_VERBOSE, BOOL_VERBOSE);
325 RuntimeOutput.print("IoTMaster: Information extracted successfully!", BOOL_VERBOSE);
329 * A method to parse information from a config file
331 * @param strCfgFileName Config file name
332 * @param strCfgField Config file field name
335 private String parseConfigFile(String strCfgFileName, String strCfgField) {
336 // Parse configuration file
337 Properties prop = new Properties();
338 File file = new File(strCfgFileName);
339 FileInputStream fis = null;
341 fis = new FileInputStream(file);
344 } catch (IOException ex) {
345 System.out.println("IoTMaster: Error reading config file: " + strCfgFileName);
346 ex.printStackTrace();
348 RuntimeOutput.print("IoTMaster: Reading " + strCfgField +
349 " from config file: " + strCfgFileName + " with value: " +
350 prop.getProperty(strCfgField, null), BOOL_VERBOSE);
351 // NULL is returned if the property isn't found
352 return prop.getProperty(strCfgField, null);
356 * A method to send files from IoTMaster
358 * @param filesocket File socket object
359 * @param sFileName File name
360 * @param lFLength File length
363 private void sendFile(Socket filesocket, String sFileName, long lFLength) throws IOException {
365 File file = new File(sFileName);
366 byte[] bytFile = new byte[toIntExact(lFLength)];
367 InputStream inFileStream = new FileInputStream(file);
369 OutputStream outFileStream = filesocket.getOutputStream();
371 while ((iCount = inFileStream.read(bytFile)) > 0) {
372 outFileStream.write(bytFile, 0, iCount);
375 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
379 * A method to create a thread
381 * @param sSSHCmd SSH command
384 private void createThread(String sSSHCmd) throws IOException {
386 // Start a new thread to start a new JVM
388 Runtime runtime = Runtime.getRuntime();
389 Process process = runtime.exec(sSSHCmd);
391 RuntimeOutput.print("Executing: " + sSSHCmd, BOOL_VERBOSE);
395 * A method to send command from master and receive reply from slave
397 * @params msgSend Message object
398 * @params strPurpose String that prints purpose message
399 * @params inStream Input stream
400 * @params outStream Output stream
403 private void commMasterToSlave(Message msgSend, String strPurpose,
404 InputStream _inStream, OutputStream _outStream)
405 throws IOException, ClassNotFoundException {
407 // Send message/command from master
408 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
409 outStream.writeObject(msgSend);
410 RuntimeOutput.print("IoTMaster: Send message: " + strPurpose, BOOL_VERBOSE);
412 // Get reply from slave as acknowledgment
413 ObjectInputStream inStream = (ObjectInputStream) _inStream;
414 Message msgReply = (Message) inStream.readObject();
415 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
419 * A private method to instrument IoTSet device
421 * @params strFieldIdentifier String field name + object ID
422 * @params strFieldName String field name
423 * @params strIoTSlaveObjectHostAdd String slave host address
424 * @params inStream ObjectInputStream communication
425 * @params outStream ObjectOutputStream communication
426 * @params strLanguage String language
429 private void instrumentIoTSetDevice(String strFieldIdentifier, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
430 InputStream inStream, OutputStream outStream, String strLanguage)
431 throws IOException, ClassNotFoundException, InterruptedException {
433 // Get information from the set
434 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
435 RuntimeOutput.print("IoTMaster: DEBUG: Getting into instrumentIoTSetDevice!", BOOL_VERBOSE);
436 // Create a new IoTSet
437 if(strLanguage.equals(STR_JAVA)) {
438 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
439 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTDeviceAddress!", inStream, outStream);
441 createNewIoTSetCpp(strFieldName, outStream, inStream);
442 int iRows = listObject.size();
443 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
444 // Transfer the address
445 for(int iRow=0; iRow<iRows; iRow++) {
446 arrFieldValues = listObject.get(iRow);
447 // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
448 String strDeviceAddress = null;
449 String strDeviceAddressKey = null;
450 if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
451 strDeviceAddress = strIoTSlaveObjectHostAdd;
452 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
454 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
455 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
457 int iDestDeviceDriverPort = (int) arrFieldValues[1];
458 String strProtocol = (String) arrFieldValues[2];
459 // Check for wildcard feature
460 boolean bSrcPortWildCard = false;
461 boolean bDstPortWildCard = false;
462 if (arrFieldValues.length > 3) {
463 bSrcPortWildCard = (boolean) arrFieldValues[3];
464 bDstPortWildCard = (boolean) arrFieldValues[4];
466 // Add the port connection into communication handler - if it's not assigned yet
467 if (commHan.getComPort(strDeviceAddressKey) == null) {
468 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
470 // Send address one by one
471 if(strLanguage.equals(STR_JAVA)) {
472 Message msgGetIoTSetObj = null;
473 if (bDstPortWildCard) {
474 String strUniqueDev = strDeviceAddressKey + ":" + iRow;
475 msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
476 strDeviceAddress, commHan.getAdditionalPort(strUniqueDev), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
478 msgGetIoTSetObj = new MessageGetDeviceObject(IoTCommCode.GET_DEVICE_IOTSET_OBJECT,
479 strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort, bSrcPortWildCard, bDstPortWildCard);
480 commMasterToSlave(msgGetIoTSetObj, "Get IoTSet objects!", inStream, outStream);
482 getDeviceIoTSetObjectCpp(outStream, inStream, strDeviceAddress, commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort,
483 bSrcPortWildCard, bDstPortWildCard);
485 // Reinitialize IoTSet on device object
486 if(strLanguage.equals(STR_JAVA))
487 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
489 reinitializeIoTSetFieldCpp(outStream, inStream);
494 * A private method to instrument IoTSet Zigbee device
496 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
497 * @params strFieldName String field name
498 * @params strIoTSlaveObjectHostAdd String slave host address
499 * @params inStream ObjectInputStream communication
500 * @params inStream ObjectOutputStream communication
501 * @params strLanguage String language
504 private void instrumentIoTSetZBDevice(Map.Entry<String,Object> map, String strObjName, String strFieldName, String strIoTSlaveObjectHostAdd,
505 InputStream inStream, OutputStream outStream, String strLanguage)
506 throws IOException, ClassNotFoundException, InterruptedException {
508 // Get information from the set
509 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
510 // Create a new IoTSet
511 if(strLanguage.equals(STR_JAVA)) {
512 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
513 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTZigbeeAddress!", inStream, outStream);
514 } else // TODO: will need to implement IoTSet Zigbee for C++ later
516 // Prepare ZigbeeConfig
517 String strZigbeeGWAddress = routerConfig.getIPFromMACAddress(STR_ZB_GATEWAY_ADDRESS);
518 String strZigbeeGWAddressKey = strObjName + "-" + strZigbeeGWAddress;
519 int iZigbeeGWPort = Integer.parseInt(STR_ZB_GATEWAY_PORT);
520 int iZigbeeIoTMasterPort = Integer.parseInt(STR_ZB_IOTMASTER_PORT);
521 commHan.addDevicePort(iZigbeeIoTMasterPort);
522 ZigbeeConfig zbConfig = new ZigbeeConfig(strZigbeeGWAddress, iZigbeeGWPort, iZigbeeIoTMasterPort,
524 // Add the port connection into communication handler - if it's not assigned yet
525 if (commHan.getComPort(strZigbeeGWAddressKey) == null) {
526 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strZigbeeGWAddressKey);
528 int iRows = setInstrumenter.numberOfRows();
529 RuntimeOutput.print("IoTMaster: Number of rows for IoTZigbeeAddress: " + iRows, BOOL_VERBOSE);
530 // Transfer the address
531 for(int iRow=0; iRow<iRows; iRow++) {
532 arrFieldValues = setInstrumenter.fieldValues(iRow);
533 // Get device address
534 String strZBDevAddress = (String) arrFieldValues[0];
535 // Send policy to Zigbee gateway - TODO: Need to clear policy first?
536 zbConfig.setPolicy(strIoTSlaveObjectHostAdd, commHan.getComPort(strZigbeeGWAddressKey), strZBDevAddress);
537 // Send address one by one
538 if(strLanguage.equals(STR_JAVA)) {
539 Message msgGetIoTSetZBObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ZB_DEV_IOTSET_OBJECT, strZBDevAddress);
540 commMasterToSlave(msgGetIoTSetZBObj, "Get IoTSet objects!", inStream, outStream);
541 } else // TODO: Implement IoTSet Zigbee for C++
544 zbConfig.closeConnection();
545 // Reinitialize IoTSet on device object
546 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD), "Reinitialize IoTSet fields!", inStream, outStream);
551 * A private method to instrument IoTSet of addresses
553 * @params strFieldIdentifier String field name + object ID
554 * @params strFieldName String field name
555 * @params inStream ObjectInputStream communication
556 * @params inStream ObjectOutputStream communication
557 * @params strLanguage String language
560 private void instrumentIoTSetAddress(String strFieldIdentifier, String strFieldName,
561 InputStream inStream, OutputStream outStream, String strLanguage)
562 throws IOException, ClassNotFoundException, InterruptedException {
564 // Get information from the set
565 List<Object[]> listObject = objAddInitHand.getFields(strFieldIdentifier);
566 // Create a new IoTSet
567 if(strLanguage.equals(STR_JAVA)) {
568 Message msgCrtIoTSet = new MessageCreateSetRelation(IoTCommCode.CREATE_NEW_IOTSET, strFieldName);
569 commMasterToSlave(msgCrtIoTSet, "Create new IoTSet for IoTAddress!", inStream, outStream);
572 int iRows = listObject.size();
573 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
574 // Transfer the address
575 for(int iRow=0; iRow<iRows; iRow++) {
576 arrFieldValues = listObject.get(iRow);
577 // Get device address
578 String strAddress = (String) arrFieldValues[0];
579 // Send address one by one
580 if(strLanguage.equals(STR_JAVA)) {
581 Message msgGetIoTSetAddObj = new MessageGetSimpleDeviceObject(IoTCommCode.GET_ADD_IOTSET_OBJECT, strAddress);
582 commMasterToSlave(msgGetIoTSetAddObj, "Get IoTSet objects!", inStream, outStream);
583 } else // TODO: Implement IoTSet Address for C++
586 // Reinitialize IoTSet on device object
587 commMasterToSlave(new MessageSimple(IoTCommCode.REINITIALIZE_IOTSET_FIELD),
588 "Reinitialize IoTSet fields!", inStream, outStream);
593 * A private method to instrument an object on a specific machine and setting up policies
595 * @params strFieldObjectID String field object ID
596 * @params strObjControllerName String object controller name
597 * @params strLanguage String language
600 private void instrumentObject(String strFieldObjectID, String strObjControllerName, String strLanguage) throws IOException {
602 // Extract the interface name for RMI
603 // e.g. ProximitySensorInterface, TempSensorInterface, etc.
604 String strObjCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
605 strObjClassInterfaceName = parseConfigFile(strObjCfgFile, STR_INTERFACE_CLS_CFG);
606 strObjStubClsIntfaceName = parseConfigFile(strObjCfgFile, STR_INT_STUB_CLS_CFG);
607 // Create an object name, e.g. ProximitySensorImplPS1
608 strObjName = strObjClassName + strFieldObjectID;
609 // Check first if host exists
610 if(commHan.objectExists(strObjName)) {
611 // If this object exists already ...
612 // Re-read IoTSlave object hostname for further reference
613 strIoTSlaveObjectHostAdd = commHan.getHostAddress(strObjName);
614 RuntimeOutput.print("IoTMaster: Object with name: " + strObjName + " has existed!", BOOL_VERBOSE);
616 // If this is a new object ... then create one
617 // Get host address for IoTSlave from LoadBalancer
618 strIoTSlaveObjectHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
619 if (strIoTSlaveControllerHostAdd == null)
620 throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
621 RuntimeOutput.print("IoTMaster: Object name: " + strObjName, BOOL_VERBOSE);
622 // Add port connection and get port numbers
623 // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
624 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strObjName);
625 commHan.addActiveControllerObject(strFieldObjectID, strObjName, strObjClassName, strObjClassInterfaceName,
626 strObjStubClsIntfaceName, strIoTSlaveObjectHostAdd, arrFieldValues, arrFieldClasses);
627 // ROUTING POLICY: IoTMaster and device/controller object
628 // Master-slave communication
629 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
630 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
631 // ROUTING POLICY: Send the same routing policy to both the hosts
632 routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
633 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
634 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTMasterHostAdd,
635 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjName));
636 // Need to accommodate callback functions here - open ports for TCP
637 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd,
638 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
639 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd,
640 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
641 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd,
642 strIoTSlaveObjectHostAdd, STR_TCP_PROTOCOL);
643 // Configure MAC policies for objects
644 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
646 String strObjLanguage = readObjectLanguage(strObjName, strObjClassName);
647 String strFileName = null;
648 if(strObjLanguage.equals(STR_JAVA))
649 strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
651 strFileName = STR_MAC_POL_PATH + STR_CPP + STR_MAC_POLICY_EXT;
652 processJailConfig.configureProcessJailDeviceDriverPolicies(strIoTSlaveObjectHostAdd, strObjName, strObjClassName,
653 strFileName, strIoTMasterHostAdd, commHan.getComPort(strObjName), commHan.getRMIRegPort(strObjName),
654 commHan.getRMIStubPort(strObjName));
655 // Check for additional MAC policy
656 String strMACConfigPath = STR_IOT_CODE_PATH + strObjClassName + "/";
657 String strCfgFile = strMACConfigPath + strObjClassName + STR_CFG_FILE_EXT;
658 String strAddMACPolicy = parseConfigFile(strCfgFile, STR_ADD_MAC_POL);
659 if (strAddMACPolicy != null && strAddMACPolicy.equals("Yes"))
660 processJailConfig.combineAdditionalMACPolicy(strMACConfigPath, strObjClassName, strIoTSlaveObjectHostAdd);
661 processJailConfig.configureProcessJailContRMIPolicies(strObjControllerName, strIoTSlaveObjectHostAdd,
662 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName));
664 // Instrument the IoTSet declarations inside the class file
665 instrumentObjectIoTSet(strFieldObjectID, strLanguage);
667 // Send routing policy to router for controller object
668 // ROUTING POLICY: RMI communication - RMI registry and stub ports
669 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
670 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
671 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
672 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
673 // Send the same set of routing policies to compute nodes
674 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
675 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
676 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
677 STR_TCP_PROTOCOL, commHan.getRMIRegPort(strObjName));
678 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
679 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
680 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveControllerHostAdd, strIoTSlaveObjectHostAdd,
681 STR_TCP_PROTOCOL, commHan.getRMIStubPort(strObjName));
686 * A private method to set router policies for IoTDeviceAddress objects
688 * @params strFieldIdentifier String field name + object ID
689 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
690 * @params strIoTSlaveObjectHostAdd String slave host address
693 private void setRouterPolicyIoTSetDevice(String strFieldIdentifier, Map.Entry<String,Object> map,
694 String strIoTSlaveObjectHostAdd) {
696 // Get information from the set
697 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
698 int iRows = setInstrumenter.numberOfRows();
699 RuntimeOutput.print("IoTMaster: Number of rows for IoTDeviceAddress: " + iRows, BOOL_VERBOSE);
700 // Transfer the address
701 for(int iRow=0; iRow<iRows; iRow++) {
702 arrFieldValues = setInstrumenter.fieldValues(iRow);
703 objAddInitHand.addField(strFieldIdentifier, arrFieldValues); // Save this for object instantiation
704 // Get device address - if 00:00:00:00:00:00 that means it needs the driver object address (self)
705 String strDeviceAddress = null;
706 String strDeviceAddressKey = null;
707 if (arrFieldValues[0].equals(STR_SELF_MAC_ADD)) {
708 strDeviceAddress = strIoTSlaveObjectHostAdd;
709 strDeviceAddressKey = strObjName + "-" + strIoTSlaveObjectHostAdd;
710 } else { // Concatenate object name and IP address to give unique key - for a case where there is one device for multiple drivers
711 strDeviceAddress = routerConfig.getIPFromMACAddress((String) arrFieldValues[0]);
712 strDeviceAddressKey = strObjName + "-" + strDeviceAddress;
714 int iDestDeviceDriverPort = (int) arrFieldValues[1];
715 String strProtocol = (String) arrFieldValues[2];
716 // Add the port connection into communication handler - if it's not assigned yet
717 if (commHan.getComPort(strDeviceAddressKey) == null)
718 commHan.addPortConnection(strIoTSlaveObjectHostAdd, strDeviceAddressKey);
719 boolean bDstPortWildCard = false;
720 // Recognize this and allocate different ports for it
721 if (arrFieldValues.length > 3) {
722 bDstPortWildCard = (boolean) arrFieldValues[4];
723 if (bDstPortWildCard) { // This needs a unique source port
724 String strUniqueDev = strDeviceAddressKey + ":" + iRow;
725 commHan.addAdditionalPort(strUniqueDev);
728 // Send routing policy to router for device drivers and devices
729 // ROUTING POLICY: RMI communication - RMI registry and stub ports
730 if((iDestDeviceDriverPort == -1) && (!strProtocol.equals(STR_NO_PROTOCOL))) {
731 // Port number -1 means that we don't set the policy strictly to port number level
732 // "nopro" = no protocol specified for just TCP or just UDP (can be both used as well)
733 // ROUTING POLICY: Device driver and device
734 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
735 // ROUTING POLICY: Send to the compute node where the device driver is
736 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol);
737 } else if((iDestDeviceDriverPort == -1) && (strProtocol.equals(STR_NO_PROTOCOL))) {
738 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
739 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
740 } else if(strProtocol.equals(STR_TCPGW_PROTOCOL)) {
741 // This is a TCP protocol that connects, e.g. a phone to our runtime system
742 // that provides a gateway access (accessed through destination port number)
743 commHan.addDevicePort(iDestDeviceDriverPort);
744 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
745 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, STR_TCP_PROTOCOL, iDestDeviceDriverPort);
746 routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress);
747 routerConfig.configureHostHTTPPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress);
748 // Configure MAC policies
749 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
750 processJailConfig.configureProcessJailGWDevicePolicies(strIoTSlaveObjectHostAdd, STR_ROUTER_ADD, strDeviceAddress, INT_DNS_PORT);
752 // Other port numbers...
753 commHan.addDevicePort(iDestDeviceDriverPort);
754 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol,
755 commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
756 routerConfig.configureHostMainPolicies(strIoTSlaveObjectHostAdd, strIoTSlaveObjectHostAdd, strDeviceAddress, strProtocol,
757 commHan.getComPort(strDeviceAddressKey), iDestDeviceDriverPort);
758 // Configure MAC policies
759 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
760 processJailConfig.configureProcessJailDevicePolicies(strIoTSlaveObjectHostAdd, strProtocol,
761 commHan.getComPort(strDeviceAddressKey), strDeviceAddress, iDestDeviceDriverPort);
767 * A private method to set router policies for IoTAddress objects
769 * @params strFieldIdentifier String field name + object ID
770 * @params Map.Entry<String,Object> Entry of map IoTSet instrumentation
771 * @params strHostAddress String host address
774 private void setRouterPolicyIoTSetAddress(String strFieldIdentifier, Map.Entry<String,Object> map,
775 String strHostAddress, String strControllerName) {
777 // Get information from the set
778 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
779 int iRows = setInstrumenter.numberOfRows();
780 RuntimeOutput.print("IoTMaster: Number of rows for IoTAddress: " + iRows, BOOL_VERBOSE);
781 // Transfer the address
782 for(int iRow=0; iRow<iRows; iRow++) {
783 arrFieldValues = setInstrumenter.fieldValues(iRow);
784 objAddInitHand.addField(strFieldIdentifier, arrFieldValues); // Save this for object instantiation
785 // Get device address
786 String strAddress = (String) arrFieldValues[0];
787 // Setting up router policies for HTTP/HTTPs
788 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
789 if (strControllerName != null) {
790 processJailConfig.configureProcessJailInetAddressPolicies(strControllerName, STR_ROUTER_ADD, strAddress);
792 processJailConfig.configureProcessJailInetAddressPolicies(strHostAddress, STR_ROUTER_ADD, strAddress);
795 routerConfig.configureRouterHTTPPolicies(STR_ROUTER_ADD, strHostAddress, strAddress);
796 routerConfig.configureHostHTTPPolicies(strHostAddress, strHostAddress, strAddress);
801 * A private method to instrument an object's IoTSet and IoTRelation field to up policies
803 * Mostly the IoTSet fields would contain IoTDeviceAddress objects
805 * @params strFieldObjectID String field object ID
806 * @params strLanguage String language
809 private void instrumentObjectIoTSet(String strFieldObjectID, String strLanguage) throws IOException {
811 // If this is a new object ... then create one
812 // Instrument the class source code and look for IoTSet for device addresses
813 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
814 HashMap<String,Object> hmObjectFieldObjects = null;
815 if(strLanguage.equals(STR_JAVA)) {
816 String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CLS_FILE_EXT;
817 FileInputStream fis = new FileInputStream(strObjectClassNamePath);
818 ClassReader cr = new ClassReader(fis);
819 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
820 // We need Object ID to instrument IoTDeviceAddress
821 ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, strFieldObjectID, BOOL_VERBOSE);
824 mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
825 hmObjectFieldObjects = crim.getFieldObjects();
827 String strObjectClassNamePath = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
828 CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strObjectClassNamePath, strFieldObjectID, BOOL_VERBOSE);
829 mapClassNameToCrim.put(strObjClassName + strFieldObjectID, crim);
830 hmObjectFieldObjects = crim.getFieldObjects();
832 // Get the object and the class names
833 // Build objects for IoTSet and IoTRelation fields in the device object classes
834 RuntimeOutput.print("IoTMaster: Going to instrument for " + strObjClassName + " with objectID " +
835 strFieldObjectID, BOOL_VERBOSE);
836 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
837 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
838 // Iterate over HashMap and choose between processing
839 String strFieldName = map.getKey();
840 String strClassName = map.getValue().getClass().getName();
841 String strFieldIdentifier = strFieldName + strFieldObjectID;
842 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
843 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
844 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
845 // Instrument the normal IoTDeviceAddress
846 setRouterPolicyIoTSetDevice(strFieldIdentifier, map, strIoTSlaveObjectHostAdd);
847 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
848 // Instrument the IoTAddress
849 setRouterPolicyIoTSetAddress(strFieldIdentifier, map, strIoTSlaveObjectHostAdd, null);
850 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
851 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
852 RuntimeOutput.print("IoTMaster: IoTZigbeeAddress found! No router policy is set here..",
855 String strErrMsg = "IoTMaster: Device driver object" +
856 " can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
857 " or IoTSet<IoTZigbeeAddress>!";
858 throw new Error(strErrMsg);
861 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
862 throw new Error(strErrMsg);
869 * A private method to send files to a Java slave driver
871 * @params serverSocket ServerSocket
872 * @params _inStream InputStream
873 * @params _outStream OutputStream
874 * @params strObjName String
875 * @params strObjClassName String
876 * @params strObjClassInterfaceName String
877 * @params strObjStubClsIntfaceName String
878 * @params strIoTSlaveObjectHostAdd String
879 * @params strFieldObjectID String
880 * @params arrFieldValues Object[]
881 * @params arrFieldClasses Class[]
884 private void sendFileToJavaSlaveDriver(ServerSocket serverSocket, InputStream _inStream, OutputStream _outStream,
885 String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
886 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses)
887 throws IOException, ClassNotFoundException {
889 ObjectInputStream inStream = (ObjectInputStream) _inStream;
890 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
891 // Create message to transfer file first
892 String sFileName = strObjClassName + STR_JAR_FILE_EXT;
893 String sPath = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
894 File file = new File(sPath);
895 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, sFileName, file.length()),
896 "Sending file!", inStream, outStream);
897 // Send file - JAR file for object creation
898 sendFile(serverSocket.accept(), sPath, file.length());
899 Message msgReply = (Message) inStream.readObject();
900 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
901 // Pack object information to create object on a IoTSlave
902 Message msgObjIoTSlave = new MessageCreateObject(IoTCommCode.CREATE_OBJECT, strIoTSlaveObjectHostAdd,
903 strObjClassName, strObjName, strObjClassInterfaceName, strObjStubClsIntfaceName, commHan.getRMIRegPort(strObjName),
904 commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses);
906 commMasterToSlave(msgObjIoTSlave, "Sending object information", inStream, outStream);
911 * A private method to send files to a Java slave driver
915 private void sendFileToCppSlaveDriver(String strObjClassName, String strIoTSlaveObjectHostAdd)
916 throws IOException, ClassNotFoundException {
918 // Create message to transfer file first
919 String sFileName = strObjClassName + STR_ZIP_FILE_EXT;
920 String sFile = STR_IOT_CODE_PATH + strObjClassName + "/" + sFileName;
921 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_SLAVE_DIR;
922 runCommand(strCmdSend);
923 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
925 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " +
926 STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
927 runCommand(strCmdUnzip);
928 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
934 * Construct command line for Java IoTSlave
938 private String getCmdJavaDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
940 // Create an Shell executable
941 String strJavaCommand = STR_SHELL_HEADER + "\nexec sudo " + STR_JAVA_PATH + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " +
942 STR_RMI_HOSTNAME + strIoTSlaveObjectHostAdd + " " + STR_IOT_SLAVE_CLS + " " + strIoTMasterHostAdd + " " +
943 commHan.getComPort(strObjName) + " " + commHan.getRMIRegPort(strObjName) + " " +
944 commHan.getRMIStubPort(strObjName) + " > " + STR_LOG_FILE_PATH + strObjName + ".log &";
945 String shellFile = "./" + strObjName + STR_SHELL_FILE_EXT;
946 createWrapperShellScript(strJavaCommand, shellFile);
947 // Send the file to the compute node
948 String strCmdSend = STR_SCP + " " + shellFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_RUNTIME_DIR;
949 runCommand(strCmdSend);
950 RuntimeOutput.print("IoTMaster: Sending shell file: " + strCmdSend, BOOL_VERBOSE);
951 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
956 * Construct command line for C++ IoTSlave
960 private String getCmdCppDriverIoTSlave(String strIoTMasterHostAdd, String strIoTSlaveObjectHostAdd, String strObjName) {
962 // Create an Shell executable
963 String strCppCommand = STR_SHELL_HEADER + "\ncd " + STR_SLAVE_DIR + " exec sudo " + STR_IOTSLAVE_CPP + " " +
964 strIoTMasterHostAdd + " " + commHan.getComPort(strObjName) + " " + strObjName;
965 String shellFile = "./" + strObjName + STR_SHELL_FILE_EXT;
966 createWrapperShellScript(strCppCommand, shellFile);
967 // Send the file to the compute node
968 String strCmdSend = STR_SCP + " " + shellFile + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + ":" + STR_RUNTIME_DIR;
969 runCommand(strCmdSend);
970 RuntimeOutput.print("IoTMaster: Sending shell file: " + strCmdSend, BOOL_VERBOSE);
971 return STR_SSH + " " + STR_USERNAME + strIoTSlaveObjectHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
976 * createWrapperShellScript() gets a wrapper shell script
978 * @param strCommand String command
979 * @param strObjectName String object name
980 * @return PrintWriter
982 private void createWrapperShellScript(String strCommand, String strFileName) {
984 PrintWriter printWriter = getPrintWriter(strFileName);
985 printWriter.println(strCommand);
987 runCommand("chmod 755 " + strFileName);
991 * A private method to read the language of the object, i.e. driver
993 * @params strObjName String object name
994 * @params strObjClassName String object class name
997 private String readObjectLanguage(String strObjName, String strObjClassName) {
1000 String sCfgFile = STR_IOT_CODE_PATH + strObjClassName + "/" + strObjClassName + STR_CFG_FILE_EXT;
1001 String strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE + "_" + strObjName);
1002 if(strLanguageDriver == null) // Read just the field LANGUAGE if the first read is null
1003 strLanguageDriver = parseConfigFile(sCfgFile, STR_LANGUAGE);
1004 if(strLanguageDriver == null) // Check nullness for the second time - report if it is still null
1005 throw new Error("IoTMaster: Language specification missing in config file: " + sCfgFile);
1007 return strLanguageDriver;
1011 * A private method to create an object on a specific machine
1013 * @params strObjName String object name
1014 * @params strObjClassName String object class name
1015 * @params strObjClassInterfaceName String object class interface name
1016 * @params strIoTSlaveObjectHostAdd String IoTSlave host address
1017 * @params strFieldObjectID String field object ID
1018 * @params arrFieldValues Array of field values
1019 * @params arrFieldClasses Array of field classes
1022 private void createObject(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strObjStubClsIntfaceName,
1023 String strIoTSlaveObjectHostAdd, String strFieldObjectID, Object[] arrFieldValues, Class[] arrFieldClasses)
1024 throws IOException, FileNotFoundException, ClassNotFoundException, InterruptedException {
1027 String strLanguageDriver = readObjectLanguage(strObjName, strObjClassName);
1028 // Construct ssh command line
1029 // e.g. ssh rtrimana@dw-2.eecs.uci.edu cd <path>;
1030 // java -cp $CLASSPATH:./*.jar
1031 // -Djava.rmi.server.codebase=file:./*.jar
1032 // iotruntime.IoTSlave dw-1.eecs.uci.edu 46151 23829 42874 &
1033 // The In-Port for IoTMaster is the Out-Port for IoTSlave and vice versa
1034 String strSSHCommand = null;
1035 if(strLanguageDriver.equals(STR_JAVA))
1036 strSSHCommand = getCmdJavaDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1037 else if(strLanguageDriver.equals(STR_CPP))
1038 strSSHCommand = getCmdCppDriverIoTSlave(strIoTMasterHostAdd, strIoTSlaveObjectHostAdd, strObjName);
1040 throw new Error("IoTMaster: Language specification not recognized: " + strLanguageDriver);
1041 RuntimeOutput.print("IoTMaster: Language for " + strObjName + " is " + strLanguageDriver, BOOL_VERBOSE);
1042 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
1043 // Start a new thread to start a new JVM
1044 createThread(strSSHCommand);
1045 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjName));
1046 Socket socket = serverSocket.accept();
1047 //InputStream inStream = new ObjectInputStream(socket.getInputStream());
1048 //OutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
1049 InputStream inStream = null;
1050 OutputStream outStream = null;
1051 if(strLanguageDriver.equals(STR_JAVA)) {
1052 inStream = new ObjectInputStream(socket.getInputStream());
1053 outStream = new ObjectOutputStream(socket.getOutputStream());
1054 } else { // At this point the language is certainly C++, otherwise would've complained above
1055 inStream = new BufferedInputStream(socket.getInputStream());
1056 outStream = new BufferedOutputStream(socket.getOutputStream());
1059 if(strLanguageDriver.equals(STR_JAVA)) {
1060 sendFileToJavaSlaveDriver(serverSocket, inStream, outStream, strObjName,
1061 strObjClassName, strObjClassInterfaceName, strObjStubClsIntfaceName,
1062 strIoTSlaveObjectHostAdd, strFieldObjectID, arrFieldValues, arrFieldClasses);
1064 sendFileToCppSlaveDriver(strObjClassName, strIoTSlaveObjectHostAdd);
1065 createObjectCpp(strObjName, strObjClassName, strObjClassInterfaceName, strIoTSlaveObjectHostAdd,
1066 commHan.getRMIRegPort(strObjName), commHan.getRMIStubPort(strObjName), arrFieldValues, arrFieldClasses,
1067 outStream, inStream);
1069 // Instrument the class source code and look for IoTSet for device addresses
1070 // e.g. @config private IoTSet<IoTDeviceAddress> lb_addresses;
1071 RuntimeOutput.print("IoTMaster: Instantiating for " + strObjClassName + " with objectID " + strFieldObjectID, BOOL_VERBOSE);
1072 // Get the object and the class names
1073 // Build objects for IoTSet and IoTRelation fields in the device object classes
1074 Object crimObj = mapClassNameToCrim.get(strObjClassName + strFieldObjectID);
1075 HashMap<String,Object> hmObjectFieldObjects = null;
1076 if (crimObj instanceof ClassRuntimeInstrumenterMaster) {
1077 ClassRuntimeInstrumenterMaster crim = (ClassRuntimeInstrumenterMaster) crimObj;
1078 hmObjectFieldObjects = crim.getFieldObjects();
1079 } else if (crimObj instanceof CRuntimeInstrumenterMaster) {
1080 CRuntimeInstrumenterMaster crim = (CRuntimeInstrumenterMaster) crimObj;
1081 hmObjectFieldObjects = crim.getFieldObjects();
1083 for(Map.Entry<String,Object> map : hmObjectFieldObjects.entrySet()) {
1084 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
1085 // Iterate over HashMap and choose between processing
1086 String strFieldName = map.getKey();
1087 String strClassName = map.getValue().getClass().getName();
1088 String strFieldIdentifier = strFieldName + strFieldObjectID;
1089 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
1090 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
1091 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
1092 // Instrument the normal IoTDeviceAddress
1093 synchronized(this) {
1094 //RuntimeOutput.print("IoTMaster: DEBUG: Processing " + STR_IOT_DEV_ADD_CLS + "!", BOOL_VERBOSE);
1095 instrumentIoTSetDevice(strFieldIdentifier, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1097 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
1098 // Instrument the IoTZigbeeAddress - special feature for Zigbee device support
1099 synchronized(this) {
1100 instrumentIoTSetZBDevice(map, strObjName, strFieldName, strIoTSlaveObjectHostAdd, inStream, outStream, strLanguageDriver);
1102 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
1103 // Instrument the IoTAddress
1104 synchronized(this) {
1105 instrumentIoTSetAddress(strFieldIdentifier, strFieldName, inStream, outStream, strLanguageDriver);
1108 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet<IoTAddress>, IoTSet<IoTDeviceAddress>," +
1109 " or IoTSet<IoTZigbeeAddress>!";
1110 throw new Error(strErrMsg);
1113 String strErrMsg = "IoTMaster: Device driver object can only have IoTSet for addresses!";
1114 throw new Error(strErrMsg);
1118 // TODO: Change this later
1119 if(strLanguageDriver.equals(STR_JAVA)) {
1120 ObjectOutputStream oStream = (ObjectOutputStream) outStream;
1121 oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
1122 } else { // C++ side for now will be running continuously because it's an infinite loop (not in a separate thread)
1123 createDriverObjectCpp(outStream, inStream);
1124 //endSessionCpp(outStream);
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 createNewIoTRelationCpp(str, outStream, inStream);
1350 List<ObjectInitInfo> listObject = objInitHand.getListObjectInitInfo(str);
1351 List<ObjectInitInfo> listSecondObject = objInitHand.getSecondObjectInitInfo(str);
1352 Iterator it = listSecondObject.iterator();
1353 for (ObjectInitInfo objInitInfo : listObject) {
1354 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (FIRST OBJECT)
1355 getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_FIRST_OBJECT, objInitInfo.getIoTSlaveObjectHostAdd(), objInitInfo.getObjectName(),
1356 objInitInfo.getObjectClassName(), objInitInfo.getObjectClassInterfaceName(), objInitInfo.getObjectStubClassInterfaceName(),
1357 objInitInfo.getRMIRegistryPort(), objInitInfo.getRMIStubPort(), outStream, inStream);
1358 ObjectInitInfo objSecObj = (ObjectInitInfo) it.next();
1359 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO FILL IN IOTRELATION (SECOND OBJECT)
1360 getIoTSetRelationObjectCpp(IoTCommCode.GET_IOTRELATION_SECOND_OBJECT, objSecObj.getIoTSlaveObjectHostAdd(), objSecObj.getObjectName(),
1361 objSecObj.getObjectClassName(), objSecObj.getObjectClassInterfaceName(), objSecObj.getObjectStubClassInterfaceName(),
1362 objSecObj.getRMIRegistryPort(), objSecObj.getRMIStubPort(), outStream, inStream);
1364 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO REINITIALIZE IOTRELATION FIELD
1365 reinitializeIoTRelationFieldCpp(outStream, inStream);
1371 * A method to set router basic policies at once
1373 * @param strRouter String router name
1376 private void setRouterBasicPolicies(String strRouter) {
1378 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1379 routerConfig.initMainPolicy(strRouter);
1380 routerConfig.combineRouterPolicies(strRouter);
1381 routerConfig.configureRouterICMPPolicies(strRouter, strMonitorHost);
1382 routerConfig.configureRouterDHCPPolicies(strRouter);
1383 routerConfig.configureRouterDNSPolicies(strRouter);
1384 routerConfig.configureRouterSSHPolicies(strRouter, strMonitorHost);
1385 routerConfig.configureRejectPolicies(strRouter);
1389 * A method to set host basic policies at once
1391 * @param strHost String host name
1394 private void setHostBasicPolicies(String strHost) {
1396 String strMonitorHost = routerConfig.getIPFromMACAddress(STR_MONITORING_HOST);
1397 routerConfig.initMainPolicy(strHost);
1398 routerConfig.combineRouterPolicies(strHost);
1399 routerConfig.configureHostDHCPPolicies(strHost);
1400 routerConfig.configureHostDNSPolicies(strHost);
1401 if (strHost.equals(strMonitorHost)) {
1402 // Check if this is the monitoring host
1403 routerConfig.configureHostICMPPolicies(strHost);
1404 routerConfig.configureHostSSHPolicies(strHost);
1406 routerConfig.configureHostICMPPolicies(strHost, strMonitorHost);
1407 routerConfig.configureHostSSHPolicies(strHost, strMonitorHost);
1409 // Apply SQL allowance policies to master host
1410 if (strHost.equals(strIoTMasterHostAdd)) {
1411 routerConfig.configureHostSQLPolicies(strHost);
1413 routerConfig.configureRejectPolicies(strHost);
1417 * A method to create a thread for policy deployment
1419 * @param strRouterAddress String router address to configure
1420 * @param setHostAddresses Set of strings for host addresses to configure
1423 private void createPolicyThreads(String strRouterAddress, Set<String> setHostAddresses) throws IOException {
1425 // Create a list of threads
1426 List<Thread> threads = new ArrayList<Thread>();
1427 // Start threads for hosts
1428 for(String strAddress : setHostAddresses) {
1429 Thread policyThread = new Thread(new Runnable() {
1431 synchronized(this) {
1432 routerConfig.sendHostPolicies(strAddress);
1436 threads.add(policyThread);
1437 policyThread.start();
1438 RuntimeOutput.print("Deploying policies for: " + strAddress, BOOL_VERBOSE);
1440 // A thread for router
1441 Thread policyThread = new Thread(new Runnable() {
1443 synchronized(this) {
1444 routerConfig.sendRouterPolicies(strRouterAddress);
1448 threads.add(policyThread);
1449 policyThread.start();
1450 RuntimeOutput.print("Deploying policies on router: " + strRouterAddress, BOOL_VERBOSE);
1452 for (Thread thread : threads) {
1455 } catch (InterruptedException ex) {
1456 ex.printStackTrace();
1462 * A method to create a thread for policy deployment
1464 * @param setHostAddresses Set of strings for host addresses to configure
1467 private void createMACPolicyThreads(Set<String> setHostAddresses) throws IOException {
1469 // Create a list of threads
1470 List<Thread> threads = new ArrayList<Thread>();
1471 // Start threads for hosts
1472 for(String strAddress : setHostAddresses) {
1473 Thread policyThread = new Thread(new Runnable() {
1475 synchronized(this) {
1476 processJailConfig.sendMACPolicies(strAddress);
1480 threads.add(policyThread);
1481 policyThread.start();
1482 RuntimeOutput.print("Deploying MAC policies for: " + strAddress, BOOL_VERBOSE);
1485 for (Thread thread : threads) {
1488 } catch (InterruptedException ex) {
1489 ex.printStackTrace();
1496 * A method to send files to Java IoTSlave
1498 * @params strObjControllerName String
1499 * @params serverSocket ServerSocket
1500 * @params inStream ObjectInputStream communication
1501 * @params outStream ObjectOutputStream communication
1504 private void sendFileToJavaSlave(String strObjControllerName, ServerSocket serverSocket,
1505 InputStream _inStream, OutputStream _outStream) throws IOException, ClassNotFoundException {
1507 ObjectInputStream inStream = (ObjectInputStream) _inStream;
1508 ObjectOutputStream outStream = (ObjectOutputStream) _outStream;
1510 String strControllerJarName = strObjControllerName + STR_JAR_FILE_EXT;
1511 String strControllerJarNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1512 strControllerJarName;
1513 File file = new File(strControllerJarNamePath);
1514 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerJarName, file.length()),
1515 "Sending file!", inStream, outStream);
1516 // Send file - Class file for object creation
1517 sendFile(serverSocket.accept(), strControllerJarNamePath, file.length());
1518 Message msgReply = (Message) inStream.readObject();
1519 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1520 // Send .zip file if additional zip file is specified
1521 String strObjCfgFile = strObjControllerName + STR_CFG_FILE_EXT;
1522 String strObjCfgFilePath = STR_CONT_PATH + strObjControllerName + "/" + strObjCfgFile;
1523 String strAdditionalFile = parseConfigFile(strObjCfgFilePath, STR_FILE_TRF_CFG);
1524 if (strAdditionalFile.equals(STR_YES)) {
1525 String strControllerCmpName = strObjControllerName + STR_ZIP_FILE_EXT;
1526 String strControllerCmpNamePath = STR_CONT_PATH + strObjControllerName + "/" +
1527 strControllerCmpName;
1528 file = new File(strControllerCmpNamePath);
1529 commMasterToSlave(new MessageSendFile(IoTCommCode.TRANSFER_FILE, strControllerCmpName, file.length()),
1530 "Sending file!", inStream, outStream);
1531 // Send file - Class file for object creation
1532 sendFile(serverSocket.accept(), strControllerCmpNamePath, file.length());
1533 msgReply = (Message) inStream.readObject();
1534 RuntimeOutput.print("IoTMaster: Reply message: " + msgReply.getMessage(), BOOL_VERBOSE);
1540 * A method to send files to C++ IoTSlave
1543 * TODO: Need to look into this (as of now, file transferred retains the "data" format,
1544 * hence it is unreadable from outside world
1546 private void sendFileToCppSlave(String sFilePath, String sFileName, Socket fileSocket,
1547 InputStream inStream, OutputStream outStream) throws IOException {
1549 sendCommCode(IoTCommCode.TRANSFER_FILE, outStream, inStream);
1551 sendString(sFileName, outStream); recvAck(inStream);
1552 File file = new File(sFilePath + sFileName);
1553 int iFileLen = toIntExact(file.length());
1554 RuntimeOutput.print("IoTMaster: Sending file " + sFileName + " with length " + iFileLen + " bytes...", BOOL_VERBOSE);
1556 sendInteger(iFileLen, outStream); recvAck(inStream);
1557 RuntimeOutput.print("IoTMaster: Sent file size!", BOOL_VERBOSE);
1558 byte[] bytFile = new byte[iFileLen];
1559 InputStream inFileStream = new FileInputStream(file);
1560 RuntimeOutput.print("IoTMaster: Opened file!", BOOL_VERBOSE);
1562 OutputStream outFileStream = fileSocket.getOutputStream();
1563 RuntimeOutput.print("IoTMaster: Got output stream!", BOOL_VERBOSE);
1565 while ((iCount = inFileStream.read(bytFile)) > 0) {
1566 outFileStream.write(bytFile, 0, iCount);
1568 RuntimeOutput.print("IoTMaster: File sent!", BOOL_VERBOSE);
1574 * A method to send files to C++ IoTSlave (now master using Process() to start
1575 * file transfer using scp)
1579 private void sendFileToCppSlave(String sFilePath, String sFileName) throws IOException {
1581 // Construct shell command to transfer file
1582 String sFile = sFilePath + sFileName;
1583 String strCmdSend = STR_SCP + " " + sFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_SLAVE_DIR;
1584 runCommand(strCmdSend);
1585 RuntimeOutput.print("IoTMaster: Executing: " + strCmdSend, BOOL_VERBOSE);
1587 String strCmdUnzip = STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " +
1588 STR_SLAVE_DIR + " sudo unzip -o " + sFileName + ";";
1589 runCommand(strCmdUnzip);
1590 RuntimeOutput.print("IoTMaster: Executing: " + strCmdUnzip, BOOL_VERBOSE);
1595 * runCommand() method runs shell command
1597 * @param strCommand String that contains command line
1600 private void runCommand(String strCommand) {
1603 Runtime runtime = Runtime.getRuntime();
1604 Process process = runtime.exec(strCommand);
1606 } catch (IOException ex) {
1607 System.out.println("RouterConfig: IOException: " + ex.getMessage());
1608 ex.printStackTrace();
1609 } catch (InterruptedException ex) {
1610 System.out.println("RouterConfig: InterruptException: " + ex.getMessage());
1611 ex.printStackTrace();
1617 * Construct command line for Java IoTSlave
1621 private String getCmdJavaIoTSlave(String strObjControllerName) {
1623 // Create an Shell executable
1624 String strJavaCommand = STR_SHELL_HEADER + "\nexec " + STR_JAVA_PATH + " " + STR_JVM_INIT_HEAP_SIZE + " " +
1625 STR_JVM_MAX_HEAP_SIZE + " " + STR_CLS_PATH + " " + STR_RMI_PATH + " " + STR_IOT_SLAVE_CLS + " " +
1626 strIoTMasterHostAdd + " " + commHan.getComPort(strObjControllerName) + " " +
1627 commHan.getRMIRegPort(strObjControllerName) + " " + commHan.getRMIStubPort(strObjControllerName) +
1628 " > " + STR_LOG_FILE_PATH + strObjControllerName + ".log &";
1629 String shellFile = "./" + strObjControllerName + STR_SHELL_FILE_EXT;
1630 createWrapperShellScript(strJavaCommand, shellFile);
1631 // Send the file to the compute node
1632 String strCmdSend = STR_SCP + " " + shellFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_RUNTIME_DIR;
1633 runCommand(strCmdSend);
1634 System.out.println("IoTMaster: Sending main controller shell file: " + strCmdSend);
1635 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
1640 * Construct command line for C++ IoTSlave
1644 private String getCmdCppIoTSlave(String strObjControllerName) {
1646 // Create an Shell executable
1647 String strCppCommand = STR_SHELL_HEADER + "\ncd " + STR_SLAVE_DIR + " exec sudo " +
1648 STR_IOTSLAVE_CPP + " " + strIoTMasterHostAdd + " " +
1649 commHan.getComPort(strObjControllerName) + " " + strObjControllerName;;
1650 String shellFile = "./" + strObjControllerName + STR_SHELL_FILE_EXT;
1651 createWrapperShellScript(strCppCommand, shellFile);
1652 // Send the file to the compute node
1653 String strCmdSend = STR_SCP + " " + shellFile + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + ":" + STR_RUNTIME_DIR;
1654 runCommand(strCmdSend);
1655 System.out.println("IoTMaster: Sending main controller shell file: " + strCmdSend);
1656 return STR_SSH + " " + STR_USERNAME + strIoTSlaveControllerHostAdd + " cd " + STR_RUNTIME_DIR + " " + shellFile;
1661 * sendInteger() sends an integer in bytes
1663 public void sendInteger(int intSend, OutputStream outStream) throws IOException {
1665 BufferedOutputStream output = (BufferedOutputStream) outStream;
1666 // Transform integer into bytes
1667 ByteBuffer bb = ByteBuffer.allocate(INT_SIZE);
1669 // Send the byte array
1670 output.write(bb.array(), 0, INT_SIZE);
1676 * recvInteger() receives integer in bytes
1678 public int recvInteger(InputStream inStream) throws IOException {
1680 BufferedInputStream input = (BufferedInputStream) inStream;
1681 // Wait until input is available
1682 while(input.available() == 0);
1683 // Read integer - 4 bytes
1684 byte[] recvInt = new byte[INT_SIZE];
1685 input.read(recvInt, 0, INT_SIZE);
1686 int retVal = ByteBuffer.wrap(recvInt).getInt();
1693 * recvString() receives String in bytes
1695 public String recvString(InputStream inStream) throws IOException {
1697 BufferedInputStream input = (BufferedInputStream) inStream;
1698 int strLen = recvInteger(inStream);
1699 // Wait until input is available
1700 while(input.available() == 0);
1701 // Read String per strLen
1702 byte[] recvStr = new byte[strLen];
1703 input.read(recvStr, 0, strLen);
1704 String retVal = new String(recvStr);
1711 * sendString() sends a String in bytes
1713 public void sendString(String strSend, OutputStream outStream) throws IOException {
1715 BufferedOutputStream output = (BufferedOutputStream) outStream;
1716 // Transform String into bytes
1717 byte[] strSendBytes = strSend.getBytes();
1718 int strLen = strSend.length();
1719 // Send the string length first
1720 sendInteger(strLen, outStream);
1721 // Send the byte array
1722 output.write(strSendBytes, 0, strLen);
1728 * Convert integer to enum
1730 public IoTCommCode getCode(int intCode) throws IOException {
1732 IoTCommCode[] commCode = IoTCommCode.values();
1733 IoTCommCode retCode = commCode[intCode];
1742 public synchronized boolean recvAck(InputStream inStream) throws IOException {
1744 int intAck = recvInteger(inStream);
1745 IoTCommCode codeAck = getCode(intAck);
1746 if (codeAck == IoTCommCode.ACKNOWLEDGED)
1756 public void sendEndTransfer(OutputStream outStream) throws IOException {
1758 int endCode = IoTCommCode.END_TRANSFER.ordinal();
1759 sendInteger(endCode, outStream);
1764 * Send communication code to C++
1766 public void sendCommCode(IoTCommCode inpCommCode, OutputStream outStream, InputStream inStream) throws IOException {
1769 IoTCommCode commCode = inpCommCode;
1770 int intCode = commCode.ordinal();
1771 // TODO: delete this later
1772 System.out.println("DEBUG: Sending " + commCode + " with ordinal: " + intCode);
1773 sendInteger(intCode, outStream); recvAck(inStream);
1778 * Create a main controller object for C++
1780 public void createMainObjectCpp(String strObjControllerName, OutputStream outStream, InputStream inStream) throws IOException {
1782 sendCommCode(IoTCommCode.CREATE_MAIN_OBJECT, outStream, inStream);
1783 String strMainObjName = strObjControllerName;
1784 sendString(strMainObjName, outStream); recvAck(inStream);
1785 RuntimeOutput.print("IoTMaster: Create a main object: " + strMainObjName, BOOL_VERBOSE);
1790 * A helper function that converts Class into String
1792 * @param strDataType String MySQL data type
1795 public String getClassConverted(Class<?> cls) {
1797 if (cls == String.class) {
1799 } else if (cls == int.class) {
1808 * A helper function that converts Object into String for transfer to C++ slave
1810 * @param obj Object to be converted
1811 * @param strClassType String Java Class type
1814 public String getObjectConverted(Object obj) {
1816 if (obj instanceof String) {
1817 return (String) obj;
1818 } else if (obj instanceof Integer) {
1819 return Integer.toString((Integer) obj);
1827 * Create a driver object for C++
1829 public void createObjectCpp(String strObjName, String strObjClassName, String strObjClassInterfaceName, String strIoTSlaveObjectHostAdd,
1830 Integer iRMIRegistryPort, Integer iRMIStubPort, Object[] arrFieldValues, Class[] arrFieldClasses,
1831 OutputStream outStream, InputStream inStream) throws IOException {
1833 sendCommCode(IoTCommCode.CREATE_OBJECT, outStream, inStream);
1834 RuntimeOutput.print("IoTMaster: Send request to create a driver object... ", BOOL_VERBOSE);
1835 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjName, BOOL_VERBOSE);
1836 sendString(strObjName, outStream); recvAck(inStream);
1837 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjClassName, BOOL_VERBOSE);
1838 sendString(strObjClassName, outStream); recvAck(inStream);
1839 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjClassInterfaceName, BOOL_VERBOSE);
1840 sendString(strObjStubClsIntfaceName, outStream); recvAck(inStream);
1841 RuntimeOutput.print("IoTMaster: Driver object skeleton class name: " + strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, BOOL_VERBOSE);
1842 sendString(strObjClassInterfaceName + STR_SKEL_CLASS_SUFFIX, outStream); recvAck(inStream);
1843 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1844 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1845 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1846 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1847 int numOfArgs = arrFieldValues.length;
1848 RuntimeOutput.print("IoTMaster: Send constructor arguments! Number of arguments: " + numOfArgs, BOOL_VERBOSE);
1849 sendInteger(numOfArgs, outStream); recvAck(inStream);
1850 for(Object obj : arrFieldValues) {
1851 String str = getObjectConverted(obj);
1852 sendString(str, outStream); recvAck(inStream);
1854 RuntimeOutput.print("IoTMaster: Send constructor argument classes!", BOOL_VERBOSE);
1855 for(Class cls : arrFieldClasses) {
1856 String str = getClassConverted(cls);
1857 sendString(str, outStream); recvAck(inStream);
1863 * Create new IoTSet for C++
1865 public void createNewIoTSetCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1867 sendCommCode(IoTCommCode.CREATE_NEW_IOTSET, outStream, inStream);
1868 RuntimeOutput.print("IoTMaster: Creating new IoTSet...", BOOL_VERBOSE);
1869 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1870 sendString(strObjFieldName, outStream); recvAck(inStream);
1875 * Create new IoTRelation for C++
1877 public void createNewIoTRelationCpp(String strObjFieldName, OutputStream outStream, InputStream inStream) throws IOException {
1879 sendCommCode(IoTCommCode.CREATE_NEW_IOTRELATION, outStream, inStream);
1880 RuntimeOutput.print("IoTMaster: Creating new IoTRelation...", BOOL_VERBOSE);
1881 RuntimeOutput.print("IoTMaster: Send object field name: " + strObjFieldName, BOOL_VERBOSE);
1882 sendString(strObjFieldName, outStream); recvAck(inStream);
1887 * Get a IoTDeviceAddress object for C++
1889 public void getDeviceIoTSetObjectCpp(OutputStream outStream, InputStream inStream,
1890 String strDeviceAddress, int iSourcePort, int iDestPort, boolean bSourceWildCard, boolean bDestWildCard) throws IOException {
1892 sendCommCode(IoTCommCode.GET_DEVICE_IOTSET_OBJECT, outStream, inStream);
1893 RuntimeOutput.print("IoTMaster: Getting IoTDeviceAddress...", BOOL_VERBOSE);
1894 sendString(strDeviceAddress, outStream); recvAck(inStream);
1895 sendInteger(iSourcePort, outStream); recvAck(inStream);
1896 sendInteger(iDestPort, outStream); recvAck(inStream);
1897 int iSourceWildCard = (bSourceWildCard ? 1 : 0);
1898 sendInteger(iSourceWildCard, outStream); recvAck(inStream);
1899 int iDestWildCard = (bDestWildCard ? 1 : 0);
1900 sendInteger(iDestWildCard, outStream); recvAck(inStream);
1901 RuntimeOutput.print("IoTMaster: Send device address: " + strDeviceAddress, BOOL_VERBOSE);
1906 * Get a IoTSet content object for C++
1908 public void getIoTSetRelationObjectCpp(IoTCommCode iotCommCode, String strIoTSlaveHostAddress, String strObjectName, String strObjectClassName,
1909 String strObjectClassInterfaceName, String strObjectStubClassInterfaceName, int iRMIRegistryPort, int iRMIStubPort,
1910 OutputStream outStream, InputStream inStream) throws IOException {
1912 sendCommCode(iotCommCode, outStream, inStream);
1913 RuntimeOutput.print("IoTMaster: Getting IoTSet object content...", BOOL_VERBOSE);
1915 RuntimeOutput.print("IoTMaster: Send host address: " + strIoTSlaveHostAddress, BOOL_VERBOSE);
1916 sendString(strIoTSlaveHostAddress, outStream); recvAck(inStream);
1917 RuntimeOutput.print("IoTMaster: Driver object name: " + strObjectName, BOOL_VERBOSE);
1918 sendString(strObjectName, outStream); recvAck(inStream);
1919 RuntimeOutput.print("IoTMaster: Driver object class name: " + strObjectClassName, BOOL_VERBOSE);
1920 sendString(strObjectClassName, outStream); recvAck(inStream);
1921 RuntimeOutput.print("IoTMaster: Driver object interface name: " + strObjectClassInterfaceName, BOOL_VERBOSE);
1922 sendString(strObjectClassInterfaceName, outStream); recvAck(inStream);
1923 RuntimeOutput.print("IoTMaster: Driver object stub class name: " + strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, BOOL_VERBOSE);
1924 sendString(strObjectStubClassInterfaceName + STR_STUB_CLASS_SUFFIX, outStream); recvAck(inStream);
1925 RuntimeOutput.print("IoTMaster: Driver object registry port: " + iRMIRegistryPort, BOOL_VERBOSE);
1926 sendInteger(iRMIRegistryPort, outStream); recvAck(inStream);
1927 RuntimeOutput.print("IoTMaster: Driver object stub port: " + iRMIStubPort, BOOL_VERBOSE);
1928 sendInteger(iRMIStubPort, outStream); recvAck(inStream);
1933 * Reinitialize IoTRelation field for C++
1935 private void reinitializeIoTRelationFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1937 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTRelation field!", BOOL_VERBOSE);
1938 sendCommCode(IoTCommCode.REINITIALIZE_IOTRELATION_FIELD, outStream, inStream);
1939 RuntimeOutput.print("IoTMaster: Reinitialize IoTRelation field!", BOOL_VERBOSE);
1944 * Reinitialize IoTSet field for C++
1946 private void reinitializeIoTSetFieldCpp(OutputStream outStream, InputStream inStream) throws IOException {
1948 RuntimeOutput.print("IoTMaster: About to Reinitialize IoTSet field!", BOOL_VERBOSE);
1949 sendCommCode(IoTCommCode.REINITIALIZE_IOTSET_FIELD, outStream, inStream);
1950 RuntimeOutput.print("IoTMaster: Reinitialize IoTSet field!", BOOL_VERBOSE);
1955 * Create driver object for C++
1957 private void createDriverObjectCpp(OutputStream outStream, InputStream inStream) throws IOException {
1959 sendCommCode(IoTCommCode.CREATE_DRIVER_OBJECT, outStream, inStream);
1960 RuntimeOutput.print("IoTMaster: Send command to create driver object!", BOOL_VERBOSE);
1965 * Invoke init() for C++
1967 private void invokeInitMethodCpp(OutputStream outStream, InputStream inStream) throws IOException {
1969 sendCommCode(IoTCommCode.INVOKE_INIT_METHOD, outStream, inStream);
1970 RuntimeOutput.print("IoTMaster: Invoke init method!", BOOL_VERBOSE);
1975 * End session for C++
1977 public void endSessionCpp(OutputStream outStream) throws IOException {
1979 // Send message to end session
1980 IoTCommCode endSessionCode = IoTCommCode.END_SESSION;
1981 int intCode = endSessionCode.ordinal();
1982 sendInteger(intCode, outStream);
1983 //RuntimeOutput.print("IoTMaster: Send request to create a main object: " + strObjName, BOOL_VERBOSE);
1984 RuntimeOutput.print("IoTMaster: Send request to end session!", BOOL_VERBOSE);
1989 * A method to assign objects to multiple JVMs, including
1990 * the controller/device object that uses other objects
1991 * in IoTSet and IoTRelation
1995 private void createObjects() {
2002 // Extract hostname for this IoTMaster from MySQL DB
2003 strIoTMasterHostAdd = routerConfig.getIPFromMACAddress(STR_MASTER_MAC_ADD);
2004 // Assign a new list of PrintWriter objects
2005 routerConfig.renewPrintWriter();
2006 HashSet<String> setAddresses = null;
2007 // Loop as we can still find controller/device classes
2008 for(int i=0; i<strObjectNames.length; i++) {
2010 start = System.currentTimeMillis();
2011 // Assign a new list of main PrintWriter objects
2012 routerConfig.renewMainPrintWriter();
2013 // Get controller names one by one
2014 String strObjControllerName = strObjectNames[i];
2015 // Use LoadBalancer to assign a host address
2016 //strIoTSlaveControllerHostAdd = lbIoT.selectHost();
2017 strIoTSlaveControllerHostAdd = routerConfig.getIPFromMACAddress(lbIoT.selectHost());
2018 if (strIoTSlaveControllerHostAdd == null)
2019 throw new Error("IoTMaster: Could not translate MAC to IP address! Please check the router's /tmp/dhcp.leases!");
2020 // == START INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2021 // Add port connection and get port numbers
2022 // Naming for objects ProximitySensor becomes ProximitySensor0, ProximitySensor1, etc.
2023 commHan.addPortConnection(strIoTSlaveControllerHostAdd, strObjControllerName);
2024 // ROUTING POLICY: IoTMaster and main controller object
2025 routerConfig.configureRouterMainPolicies(STR_ROUTER_ADD, strIoTMasterHostAdd,
2026 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2027 // ROUTING POLICY: Send the same routing policy to both the hosts
2028 routerConfig.configureHostMainPolicies(strIoTMasterHostAdd, strIoTMasterHostAdd,
2029 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2030 routerConfig.configureHostMainPolicies(strIoTSlaveControllerHostAdd, strIoTMasterHostAdd,
2031 strIoTSlaveControllerHostAdd, STR_TCP_PROTOCOL, commHan.getComPort(strObjControllerName));
2033 String strControllerCfg = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2034 STR_LANGUAGE_CONTROLLER = parseConfigFile(strControllerCfg, STR_LANGUAGE);
2035 if(STR_LANGUAGE_CONTROLLER == null)
2036 throw new Error("IoTMaster: Language specification missing in config file: " + strControllerCfg);
2037 // Construct ssh command line and create a controller thread for e.g. AcmeProximity
2038 String strSSHCommand = null;
2039 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2040 strSSHCommand = getCmdJavaIoTSlave(strObjControllerName);
2041 else if(STR_LANGUAGE_CONTROLLER.equals(STR_CPP))
2042 strSSHCommand = getCmdCppIoTSlave(strObjControllerName);
2044 throw new Error("IoTMaster: Language specification not recognized: " + STR_LANGUAGE_CONTROLLER);
2045 RuntimeOutput.print(strSSHCommand, BOOL_VERBOSE);
2046 createThread(strSSHCommand);
2047 // Wait for connection
2048 // Create a new socket for communication
2049 ServerSocket serverSocket = new ServerSocket(commHan.getComPort(strObjControllerName));
2050 Socket socket = serverSocket.accept();
2051 InputStream inStream = null;
2052 OutputStream outStream = null;
2053 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2054 inStream = new ObjectInputStream(socket.getInputStream());
2055 outStream = new ObjectOutputStream(socket.getOutputStream());
2056 } else { // At this point the language is certainly C++, otherwise would've complained above
2057 inStream = new BufferedInputStream(socket.getInputStream());
2058 outStream = new BufferedOutputStream(socket.getOutputStream());
2061 RuntimeOutput.print("IoTMaster: Communication established!", BOOL_VERBOSE);
2062 // Send files for every controller class
2063 // e.g. AcmeProximity.jar and AcmeProximity.zip
2064 String strControllerClassName = strObjControllerName + STR_CLS_FILE_EXT;
2065 String strControllerClassNamePath = STR_CONT_PATH + strObjControllerName + "/" +
2066 strControllerClassName;
2068 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2069 sendFileToJavaSlave(strObjControllerName, serverSocket, inStream, outStream);
2070 // Create main controller/device object
2071 commMasterToSlave(new MessageCreateMainObject(IoTCommCode.CREATE_MAIN_OBJECT, strObjControllerName),
2072 "Create main object!", inStream, outStream);
2074 String strControllerZipFile = strObjControllerName + STR_ZIP_FILE_EXT;
2075 String strControllerFilePath = STR_CONT_PATH + strObjControllerName + "/";
2076 sendFileToCppSlave(strControllerFilePath, strControllerZipFile);
2077 createMainObjectCpp(strObjControllerName, outStream, inStream);
2079 // Write basic MAC policies for controller
2080 if (STR_ACTIVATE_SANDBOXING.equals("Yes")) {
2081 String strFileName = null;
2082 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2083 strFileName = STR_MAC_POL_PATH + STR_JAVA + STR_MAC_POLICY_EXT;
2085 strFileName = STR_MAC_POL_PATH + STR_CPP + STR_MAC_POLICY_EXT;
2086 processJailConfig.configureProcessJailControllerPolicies(strObjControllerName, strFileName,
2087 strIoTMasterHostAdd, commHan.getComPort(strObjControllerName));
2088 // Whether or not we need additional Tomoyo policy?
2089 String strAddMACPolicy = parseConfigFile(strControllerCfg, STR_ADD_MAC_POL);
2090 if (strAddMACPolicy != null && strAddMACPolicy.equals("Yes")) {
2091 String strContMACCfg = STR_CONT_PATH + strObjControllerName + "/";
2092 processJailConfig.combineAdditionalMACPolicy(strContMACCfg, strObjControllerName, strObjControllerName);
2095 // == END INITIALIZING CONTROLLER/DEVICE IOTSLAVE ==
2096 // Instrumenting one file
2097 RuntimeOutput.print("IoTMaster: Opening class file: " + strControllerClassName, BOOL_VERBOSE);
2098 RuntimeOutput.print("IoTMaster: Class file path: " + strControllerClassNamePath, BOOL_VERBOSE);
2099 HashMap<String,Object> hmControllerFieldObjects = null;
2100 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2101 FileInputStream fis = new FileInputStream(strControllerClassNamePath);
2102 ClassReader cr = new ClassReader(fis);
2103 ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
2104 ClassRuntimeInstrumenterMaster crim = new ClassRuntimeInstrumenterMaster(cw, null, BOOL_VERBOSE);
2107 hmControllerFieldObjects = crim.getFieldObjects();
2109 String strControllerConfigFile = STR_CONT_PATH + strObjControllerName + "/" + strObjControllerName + STR_CFG_FILE_EXT;
2110 CRuntimeInstrumenterMaster crim = new CRuntimeInstrumenterMaster(strControllerConfigFile, null, BOOL_VERBOSE);
2111 hmControllerFieldObjects = crim.getFieldObjects();
2113 // Get the object and the class names
2114 // Build objects for IoTSet and IoTRelation fields in the controller/device classes
2115 //HashMap<String,Object> hmControllerFieldObjects = crim.getFieldObjects();
2116 for(Map.Entry<String,Object> map : hmControllerFieldObjects.entrySet()) {
2117 RuntimeOutput.print("IoTMaster: Object name: " + map.getValue().getClass().getName(), BOOL_VERBOSE);
2118 // Iterate over HashMap and choose between processing
2119 // SetInstrumenter vs. RelationInstrumenter
2120 String strFieldName = map.getKey();
2121 String strClassName = map.getValue().getClass().getName();
2122 if(strClassName.equals(STR_SET_INSTRUMENTER_CLS)) {
2123 SetInstrumenter setInstrumenter = (SetInstrumenter) map.getValue();
2124 if(setInstrumenter.getObjTableName().equals(STR_IOT_DEV_ADD_CLS)) {
2125 String strErrMsg = "IoTMaster: Controller object" +
2126 " cannot have IoTSet<IoTDeviceAddress>!";
2127 throw new Error(strErrMsg);
2128 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ZB_ADD_CLS)) {
2129 String strErrMsg = "IoTMaster: Controller object" +
2130 " cannot have IoTSet<ZigbeeAddress>!";
2131 throw new Error(strErrMsg);
2132 } else if(setInstrumenter.getObjTableName().equals(STR_IOT_ADD_CLS)) {
2133 // Instrument the IoTAddress
2134 setRouterPolicyIoTSetAddress(strFieldName, map, strIoTSlaveControllerHostAdd, strObjControllerName);
2135 instrumentIoTSetAddress(strFieldName, strFieldName, inStream, outStream, STR_LANGUAGE_CONTROLLER);
2138 instrumentIoTSet(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2140 } else if (strClassName.equals(STR_REL_INSTRUMENTER_CLS)) {
2141 instrumentIoTRelation(map, strFieldName, strObjControllerName, STR_LANGUAGE_CONTROLLER);
2144 // Combine controller MAC policies with the main policy file for the host
2145 String strTempFileName = "./" + strObjControllerName + STR_MAC_POLICY_EXT;
2146 processJailConfig.combineControllerMACPolicies(strIoTSlaveControllerHostAdd, strObjControllerName, strTempFileName);
2147 processJailConfig.flush();
2148 // ROUTING POLICY: implement basic policies to reject all other irrelevant traffics
2149 for(String s: commHan.getHosts()) {
2150 setHostBasicPolicies(s);
2152 // We retain all the basic policies for router,
2153 // but we delete the initial allowance policies for internal all TCP and UDP communications
2154 setRouterBasicPolicies(STR_ROUTER_ADD);
2155 routerConfig.closeMain();
2156 // Deploy the policy
2157 setAddresses = new HashSet<String>(commHan.getHosts());
2158 setAddresses.add(strIoTMasterHostAdd);
2159 // See if firewall policy is configured to be "on" or "off"
2160 if (STR_POLICY_ON.equals(STR_YES))
2161 createPolicyThreads(STR_ROUTER_ADD, setAddresses);
2162 // Separating object creations and Set/Relation initializations
2163 createDriverObjects();
2164 // Sets and relations initializations
2165 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2166 initializeSetsAndRelationsJava(inStream, outStream);
2168 initializeSetsAndRelationsCpp(inStream, outStream);;
2169 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA))
2170 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO EXECUTE INIT METHOD
2171 commMasterToSlave(new MessageSimple(IoTCommCode.INVOKE_INIT_METHOD), "Invoke init() method!", inStream, outStream);
2173 invokeInitMethodCpp(outStream, inStream);
2174 // == COMMUNICATION WITH IOTSLAVE CONTROLLER TO END PROCESS
2175 if(STR_LANGUAGE_CONTROLLER.equals(STR_JAVA)) {
2176 ObjectOutputStream oStream = (ObjectOutputStream) outStream;
2177 oStream.writeObject(new MessageSimple(IoTCommCode.END_SESSION));
2178 } else // C++ side will wait until the program finishes, it's not generating a separate thread for now
2179 //endSessionCpp(outStream);
2183 serverSocket.close();
2184 objInitHand.clearObjectInitHandler();
2185 commHan.printLists();
2186 commHan.clearCommunicationHandler();
2187 lbIoT.printHostInfo();
2189 // Close access to policy files and deploy policies
2190 routerConfig.close();
2191 processJailConfig.close();
2192 if (STR_ACTIVATE_SANDBOXING.equals("Yes"))
2193 createMACPolicyThreads(setAddresses);
2195 } catch (IOException |
2196 InterruptedException |
2197 ClassNotFoundException ex) {
2198 System.out.println("IoTMaster: Exception: "
2200 ex.printStackTrace();
2204 public static void main(String args[]) {
2206 // Detect the available controller/device classes
2207 // Input args[] should be used to list the controllers/devices
2208 // e.g. java IoTMaster AcmeProximity AcmeThermostat AcmeVentController
2209 IoTMaster iotMaster = new IoTMaster(args);
2211 iotMaster.parseIoTMasterConfigFile();
2212 // Initialize CommunicationHandler, LoadBalancer, and RouterConfig
2213 iotMaster.initLiveDataStructure();
2215 iotMaster.createObjects();