diff --git a/client/pom.xml b/client/pom.xml
index ac181a7d..62645098 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -16,7 +16,7 @@
org.eclipse
iofog-agent
- 1.0.3
+ 1.0.4
../pom.xml
diff --git a/client/src/org/eclipse/iofog/Client.java b/client/src/org/eclipse/iofog/Client.java
index cfb24833..4bacdc5b 100644
--- a/client/src/org/eclipse/iofog/Client.java
+++ b/client/src/org/eclipse/iofog/Client.java
@@ -95,80 +95,86 @@ private static boolean sendCommandlineParameters(String... args) {
* @return String
*/
private static String showHelp() {
-
- return ("Usage 1: iofog-agent [OPTION]\n" + "Usage 2: iofog-agent [COMMAND] \n"
- + "Usage 3: iofog-agent [COMMAND] [Parameter] \n" + "\n"
- + "Option GNU long option Meaning\n"
- + "====== =============== =======\n"
- + "-h, -? --help Show this message\n"
- + "-v --version Display the software version and\n"
- + " license information\n" + "\n" + "\n"
- + "Command Arguments Meaning\n"
- + "======= ========= =======\n"
- + "help Show this message\n"
- + "version Display the software version and\n"
- + " license information\n"
- + "status Display current status information\n"
- + " about the software\n"
- + "provision Attach this software to the\n"
- + " configured ioFog controller\n"
- + "deprovision Detach this software from all\n"
- + " ioFog controllers\n"
- + "info Display the current configuration\n"
- + " and other information about the\n"
- + " software\n"
- + "login -u Login to Oro Networks application\n"
- + " -p \n"
- + "config [Parameter] [VALUE] Change the software configuration\n"
- + " according to the options provided\n"
- + " defaults Reset configuration to default values\n"
- + " -d <#GB Limit> Set the limit, in GiB, of disk space\n"
- + " that the software is allowed to use\n"
- + " -dl Set the directory to use for disk\n"
- + " storage\n"
- + " -m <#MB Limit> Set the limit, in MiB, of RAM memory that\n"
- + " the software is allowed to use for\n"
- + " messages\n"
- + " -p <#cpu % Limit> Set the limit, in percentage, of CPU\n"
- + " time that the software is allowed\n"
- + " to use\n"
- + " -a Set the uri of the fog controller\n"
- + " to which this software connects\n"
- + " -ac Set the file path of the SSL/TLS\n"
- + " certificate for validating the fog\n"
- + " controller identity\n"
- + " -c Set the UNIX socket or network address\n"
- + " that the Docker daemon is using\n"
- + " -n Set the name of the network adapter\n"
- + " that holds the correct IP address of \n"
- + " this machine\n"
- + " -l <#MB Limit> Set the limit, in MiB, of disk space\n"
- + " that the log files can consume\n"
- + " -ld Set the directory to use for log file\n"
- + " storage\n"
- + " -lc <#log files> Set the number of log files to evenly\n"
- + " split the log storage limit\n"
- + " -sf <#seconds> Set the status update frequency\n"
- + " -cf <#seconds> Set the get changes frequency\n"
- + " -df <#seconds> Set the post diagnostics frequency\n"
- + " -idc Set the mode on which any not\\n"
- + " registered docker container will be\n"
- + " shutted down\n" + "\n" + "\n"
- + " -gps Use auto to detect fog type by system commands,\n"
- + " use arm or intel_amd to set it manually\n"
- + " -dev Set the developer's mode without using ssl \\n"
- + " certificates. \\n" + "\n" + "\n"
- + "Report bugs to: edgemaster@iofog.org\n" + "ioFog Agent home page: http://iofog.org\n"
- + "For users with Eclipse accounts, report bugs to: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=iofog");
+ return ("Usage 1: iofog-agent [OPTION]\\n" +
+ "Usage 2: iofog-agent [COMMAND] \\n" +
+ "Usage 3: iofog-agent [COMMAND] [Parameter] \\n" +
+ "\\n" +
+ "Option GNU long option Meaning\\n" +
+ "====== =============== =======\\n" +
+ "-h, -? --help Show this message\\n" +
+ "-v --version Display the software version and\\n" +
+ " license information\\n" +
+ "\\n" +
+ "\\n" +
+ "Command Arguments Meaning\\n" +
+ "======= ========= =======\\n" +
+ "help Show this message\\n" +
+ "version Display the software version and\\n" +
+ " license information\\n" +
+ "status Display current status information\\n" +
+ " about the software\\n" +
+ "provision Attach this software to the\\n" +
+ " configured ioFog controller\\n" +
+ "deprovision Detach this software from all\\n" +
+ " ioFog controllers\\n" +
+ "info Display the current configuration\\n" +
+ " and other information about the\\n" +
+ " software\\n" +
+ "switch Switch to different config \\n" +
+ "config [Parameter] [VALUE] Change the software configuration\\n" +
+ " according to the options provided\\n" +
+ " defaults Reset configuration to default values\\n" +
+ " -d <#GB Limit> Set the limit, in GiB, of disk space\\n" +
+ " that the software is allowed to use\\n" +
+ " -dl Set the directory to use for disk\\n" +
+ " storage\\n" +
+ " -m <#MB Limit> Set the limit, in MiB, of RAM memory that\\n" +
+ " the software is allowed to use for\\n" +
+ " messages\\n" +
+ " -p <#cpu % Limit> Set the limit, in percentage, of CPU\\n" +
+ " time that the software is allowed\\n" +
+ " to use\\n" +
+ " -a Set the uri of the fog controller\\n" +
+ " to which this software connects\\n" +
+ " -ac Set the file path of the SSL/TLS\\n" +
+ " certificate for validating the fog\\n" +
+ " controller identity\\n" +
+ " -c Set the UNIX socket or network address\\n" +
+ " that the Docker daemon is using\\n" +
+ " -n Set the name of the network adapter\\n" +
+ " that holds the correct IP address of \\n" +
+ " this machine\\n" +
+ " -l <#MB Limit> Set the limit, in MiB, of disk space\\n" +
+ " that the log files can consume\\n" +
+ " -ld Set the directory to use for log file\\n" +
+ " storage\\n" +
+ " -lc <#log files> Set the number of log files to evenly\\n" +
+ " split the log storage limit\\n" +
+ " -sf <#seconds> Set the status update frequency\\n" +
+ " -cf <#seconds> Set the get changes frequency\\n" +
+ " -df <#seconds> Set the post diagnostics frequency\\n" +
+ " -sd <#seconds> Set the scan devices frequency\\n" +
+ " -idc Set the mode on which any not\\n" +
+ " registered docker container will be\\n" +
+ " shut down\\n" +
+ " -gps Use auto to detect fog type by system commands,\\n" +
+ " use arm or intel_amd to set it manually\\n" +
+ " -dev Set the developer's mode without using ssl \\n" +
+ " certificates. \\n" +
+ "\\n" +
+ "\\n" +
+ "Report bugs to: edgemaster@iofog.org\\n" +
+ "ioFog home page: http://iofog.org\\n" +
+ "For users with Eclipse accounts, report bugs to: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=iofog");
}
private static String version() {
- return "ioFog Agent 1.0.0 " +
+ return "ioFog Agent 1.0.4 " +
"\nCopyright (C) 2018 Edgeworx, Inc." +
"\nEclipse ioFog is provided under the Eclipse Public License (EPL2)" +
"\nhttps://www.eclipse.org/legal/epl-v20.html";
diff --git a/daemon/pom.xml b/daemon/pom.xml
index 40b52356..ee9ba886 100644
--- a/daemon/pom.xml
+++ b/daemon/pom.xml
@@ -16,7 +16,7 @@
org.eclipse
iofog-agent
- 1.0.3
+ 1.0.4
../pom.xml
@@ -117,8 +117,13 @@
org.hornetq
- hornetq-core
- 2.3.0.BETA1
+ hornetq-core-client
+ 2.3.0.Final
+
+
+ org.hornetq
+ hornetq-server
+ 2.3.0.Final
org.glassfish
diff --git a/daemon/src/org/eclipse/iofog/Daemon.java b/daemon/src/org/eclipse/iofog/Daemon.java
index 07ebace9..9ce23a46 100644
--- a/daemon/src/org/eclipse/iofog/Daemon.java
+++ b/daemon/src/org/eclipse/iofog/Daemon.java
@@ -108,22 +108,6 @@ private static void setupEnvironment() {
daemonFilePath.mkdirs();
}
- /**
- * loads config.xml
- */
- private static void loadConfiguration() {
- try {
- Configuration.loadConfig();
- } catch (ConfigurationItemException e) {
- System.out.println("invalid configuration item(s).");
- System.out.println(e.getMessage());
- System.exit(1);
- } catch (Exception e) {
- System.out.println("Error while parsing " + Constants.CONFIG_DIR + ". " + e.getMessage());
- System.exit(1);
- }
- }
-
/**
* starts logging service
*/
@@ -165,7 +149,7 @@ public void write(int b) {
}
public static void main(String[] args) throws ParseException {
- loadConfiguration();
+ Configuration.load();
setupEnvironment();
@@ -183,14 +167,8 @@ public static void main(String[] args) throws ParseException {
outToNull();
- LoggingService.logInfo(MODULE_NAME, "starting supervisor");
- Supervisor supervisor = new Supervisor();
- try {
- supervisor.start();
- } catch (Exception exp) {
- LoggingService.logWarning(MODULE_NAME, exp.getMessage());
- }
-
+ Configuration.setupSupervisor();
+
System.setOut(Constants.systemOut);
}
}
diff --git a/daemon/src/org/eclipse/iofog/command_line/CommandLineAction.java b/daemon/src/org/eclipse/iofog/command_line/CommandLineAction.java
index d1e07207..9175c298 100644
--- a/daemon/src/org/eclipse/iofog/command_line/CommandLineAction.java
+++ b/daemon/src/org/eclipse/iofog/command_line/CommandLineAction.java
@@ -14,6 +14,8 @@
package org.eclipse.iofog.command_line;
import org.eclipse.iofog.field_agent.FieldAgent;
+import org.eclipse.iofog.utils.Constants.ConfigSwitcherState;
+import org.eclipse.iofog.utils.configuration.Configuration;
import org.eclipse.iofog.utils.logging.LoggingService;
import javax.json.JsonObject;
@@ -127,6 +129,27 @@ public String perform(String[] args) {
return getConfigReport();
}
},
+ SWITCH_ACTION {
+ @Override
+ public List getKeys() {
+ return singletonList("switch");
+ }
+
+ @Override
+ public String perform(String[] args) {
+ if (args.length < 2) {
+ return showHelp();
+ }
+
+ String environment = args[1];
+ try {
+ ConfigSwitcherState state = ConfigSwitcherState.parse(environment);
+ return Configuration.setupConfigSwitcher(state);
+ } catch(Exception e) {
+ return e.getMessage();
+ }
+ }
+ },
PROVISION_ACTION {
@Override
public List getKeys() {
@@ -200,7 +223,8 @@ public String perform(String[] args) {
try {
- HashMap oldValuesMap = getOldNodeValuesForParameters(config.keySet());
+ HashMap oldValuesMap = getOldNodeValuesForParameters(config.keySet(),
+ Configuration.getCurrentConfig());
HashMap errorMap = setConfig(config, false);
for (Map.Entry e : errorMap.entrySet())
@@ -244,81 +268,82 @@ public static CommandLineAction getActionByKey(String cmdKey) {
public static final String MODULE_NAME = "Command Line Parser";
private static String showHelp() {
- return ("Usage 1: iofog [OPTION]\\n" +
- "Usage 2: iofog [COMMAND] \\n" +
- "Usage 3: iofog [COMMAND] [Parameter] \\n" +
- "\\n" +
- "Option GNU long option Meaning\\n" +
- "====== =============== =======\\n" +
- "-h, -? --help Show this message\\n" +
- "-v --version Display the software version and\\n" +
- " license information\\n" +
- "\\n" +
- "\\n" +
- "Command Arguments Meaning\\n" +
- "======= ========= =======\\n" +
- "help Show this message\\n" +
- "version Display the software version and\\n" +
- " license information\\n" +
- "status Display current status information\\n" +
- " about the software\\n" +
- "provision Attach this software to the\\n" +
- " configured ioFog controller\\n" +
- "deprovision Detach this software from all\\n" +
- " ioFog controllers\\n" +
- "info Display the current configuration\\n" +
- " and other information about the\\n" +
- " software\\n" +
- "config [Parameter] [VALUE] Change the software configuration\\n" +
- " according to the options provided\\n" +
- " defaults Reset configuration to default values\\n" +
- " -d <#GB Limit> Set the limit, in GiB, of disk space\\n" +
- " that the software is allowed to use\\n" +
- " -dl Set the directory to use for disk\\n" +
- " storage\\n" +
- " -m <#MB Limit> Set the limit, in MiB, of RAM memory that\\n" +
- " the software is allowed to use for\\n" +
- " messages\\n" +
- " -p <#cpu % Limit> Set the limit, in percentage, of CPU\\n" +
- " time that the software is allowed\\n" +
- " to use\\n" +
- " -a Set the uri of the fog controller\\n" +
- " to which this software connects\\n" +
- " -ac Set the file path of the SSL/TLS\\n" +
- " certificate for validating the fog\\n" +
- " controller identity\\n" +
- " -c Set the UNIX socket or network address\\n" +
- " that the Docker daemon is using\\n" +
- " -n Set the name of the network adapter\\n" +
- " that holds the correct IP address of \\n" +
- " this machine\\n" +
- " -l <#MB Limit> Set the limit, in MiB, of disk space\\n" +
- " that the log files can consume\\n" +
- " -ld Set the directory to use for log file\\n" +
- " storage\\n" +
- " -lc <#log files> Set the number of log files to evenly\\n" +
- " split the log storage limit\\n" +
- " -sf <#seconds> Set the status update frequency\\n" +
- " -cf <#seconds> Set the get changes frequency\\n" +
- " -df <#seconds> Set the post diagnostics frequency\\n" +
- " -sd <#seconds> Set the scan devices frequency\\n" +
- " -idc Set the mode on which any not\\n" +
- " registered docker container will be\\n" +
- " shut down\\n" +
- " -gps Use auto to detect fog type by system commands,\\n" +
- " use arm or intel_amd to set it manually\\n" +
- " -dev Set the developer's mode without using ssl \\n" +
- " certificates. \\n" +
- "\\n" +
- "\\n" +
- "Report bugs to: edgemaster@iofog.org\\n" +
- "ioFog home page: http://iofog.org\\n" +
- "For users with Eclipse accounts, report bugs to: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=iofog");
+ return ("Usage 1: iofog-agent [OPTION]\\n" +
+ "Usage 2: iofog-agent [COMMAND] \\n" +
+ "Usage 3: iofog-agent [COMMAND] [Parameter] \\n" +
+ "\\n" +
+ "Option GNU long option Meaning\\n" +
+ "====== =============== =======\\n" +
+ "-h, -? --help Show this message\\n" +
+ "-v --version Display the software version and\\n" +
+ " license information\\n" +
+ "\\n" +
+ "\\n" +
+ "Command Arguments Meaning\\n" +
+ "======= ========= =======\\n" +
+ "help Show this message\\n" +
+ "version Display the software version and\\n" +
+ " license information\\n" +
+ "status Display current status information\\n" +
+ " about the software\\n" +
+ "provision Attach this software to the\\n" +
+ " configured ioFog controller\\n" +
+ "deprovision Detach this software from all\\n" +
+ " ioFog controllers\\n" +
+ "info Display the current configuration\\n" +
+ " and other information about the\\n" +
+ " software\\n" +
+ "switch Switch to different config \\n" +
+ "config [Parameter] [VALUE] Change the software configuration\\n" +
+ " according to the options provided\\n" +
+ " defaults Reset configuration to default values\\n" +
+ " -d <#GB Limit> Set the limit, in GiB, of disk space\\n" +
+ " that the software is allowed to use\\n" +
+ " -dl Set the directory to use for disk\\n" +
+ " storage\\n" +
+ " -m <#MB Limit> Set the limit, in MiB, of RAM memory that\\n" +
+ " the software is allowed to use for\\n" +
+ " messages\\n" +
+ " -p <#cpu % Limit> Set the limit, in percentage, of CPU\\n" +
+ " time that the software is allowed\\n" +
+ " to use\\n" +
+ " -a Set the uri of the fog controller\\n" +
+ " to which this software connects\\n" +
+ " -ac Set the file path of the SSL/TLS\\n" +
+ " certificate for validating the fog\\n" +
+ " controller identity\\n" +
+ " -c Set the UNIX socket or network address\\n" +
+ " that the Docker daemon is using\\n" +
+ " -n Set the name of the network adapter\\n" +
+ " that holds the correct IP address of \\n" +
+ " this machine\\n" +
+ " -l <#MB Limit> Set the limit, in MiB, of disk space\\n" +
+ " that the log files can consume\\n" +
+ " -ld Set the directory to use for log file\\n" +
+ " storage\\n" +
+ " -lc <#log files> Set the number of log files to evenly\\n" +
+ " split the log storage limit\\n" +
+ " -sf <#seconds> Set the status update frequency\\n" +
+ " -cf <#seconds> Set the get changes frequency\\n" +
+ " -df <#seconds> Set the post diagnostics frequency\\n" +
+ " -sd <#seconds> Set the scan devices frequency\\n" +
+ " -idc Set the mode on which any not\\n" +
+ " registered docker container will be\\n" +
+ " shut down\\n" +
+ " -gps Use auto to detect fog type by system commands,\\n" +
+ " use arm or intel_amd to set it manually\\n" +
+ " -dev Set the developer's mode without using ssl \\n" +
+ " certificates. \\n" +
+ "\\n" +
+ "\\n" +
+ "Report bugs to: edgemaster@iofog.org\\n" +
+ "ioFog home page: http://iofog.org\\n" +
+ "For users with Eclipse accounts, report bugs to: https://bugs.eclipse.org/bugs/enter_bug.cgi?product=iofog");
}
}
\ No newline at end of file
diff --git a/daemon/src/org/eclipse/iofog/command_line/CommandLineConfigParam.java b/daemon/src/org/eclipse/iofog/command_line/CommandLineConfigParam.java
index 0fc68d9b..aa5d577c 100644
--- a/daemon/src/org/eclipse/iofog/command_line/CommandLineConfigParam.java
+++ b/daemon/src/org/eclipse/iofog/command_line/CommandLineConfigParam.java
@@ -46,7 +46,7 @@ public enum CommandLineConfigParam {
STATUS_FREQUENCY("10", "sf", "status_update_freq", "statusFrequency"),
CHANGE_FREQUENCY("20", "cf", "get_changes_freq", "changeFrequency"),
DEVICE_SCAN_FREQUENCY("60", "sd", "scan_devices_freq", "deviceScanFrequency"),
- WATCHDOG_ENABLED("on", "idc", "watchdogEnabled", "watchdogEnabled"),
+ WATCHDOG_ENABLED("off", "idc", "isolated_docker_container", "watchdogEnabled"),
GPS_MODE ("", "", "", "gpsMode"),
GPS_COORDINATES (GpsMode.AUTO.name().toLowerCase(), "gps", "gps", "gpscoordinates"),
POST_DIAGNOSTICS_FREQ ("10", "df", "post_diagnostics_freq", "postdiagnosticsfreq"),
diff --git a/daemon/src/org/eclipse/iofog/field_agent/FieldAgent.java b/daemon/src/org/eclipse/iofog/field_agent/FieldAgent.java
index 7cb7f9a7..394ef576 100644
--- a/daemon/src/org/eclipse/iofog/field_agent/FieldAgent.java
+++ b/daemon/src/org/eclipse/iofog/field_agent/FieldAgent.java
@@ -921,10 +921,6 @@ public String deProvision() {
return "\nFailure - not provisioned";
}
- if (!isControllerConnected(false)) {
- return "\nFailure - not connected to controller";
- }
-
StatusReporter.setFieldAgentStatus().setControllerStatus(NOT_PROVISIONED);
try {
Configuration.setIofogUuid("");
diff --git a/daemon/src/org/eclipse/iofog/message_bus/MessageBusServer.java b/daemon/src/org/eclipse/iofog/message_bus/MessageBusServer.java
index cec85de3..fe33cf8c 100644
--- a/daemon/src/org/eclipse/iofog/message_bus/MessageBusServer.java
+++ b/daemon/src/org/eclipse/iofog/message_bus/MessageBusServer.java
@@ -96,7 +96,7 @@ void startServer() throws Exception {
configuration.setPersistenceEnabled(false);
configuration.setSecurityEnabled(false);
configuration.setPagingDirectory(workingDirectory + "messages/paging");
- configuration.getAddressesSettings().put(Constants.address, addressSettings);
+ configuration.getAddressesSettings().put(Constants.ADDRESS, addressSettings);
Map connectionParams = new HashMap<>();
connectionParams.put("port", 55555);
@@ -127,18 +127,18 @@ void startServer() throws Exception {
*/
void initialize() throws Exception {
messageBusSession = sf.createSession(true, true, 0);
- QueueQuery queueQuery = messageBusSession.queueQuery(new SimpleString(Constants.address));
+ QueueQuery queueQuery = messageBusSession.queueQuery(new SimpleString(Constants.ADDRESS));
if (queueQuery.isExists())
- messageBusSession.deleteQueue(Constants.address);
- queueQuery = messageBusSession.queueQuery(new SimpleString(Constants.commandlineAddress));
+ messageBusSession.deleteQueue(Constants.ADDRESS);
+ queueQuery = messageBusSession.queueQuery(new SimpleString(Constants.COMMAND_LINE_ADDRESS));
if (queueQuery.isExists())
- messageBusSession.deleteQueue(Constants.commandlineAddress);
- messageBusSession.createQueue(Constants.address, Constants.address, false);
- messageBusSession.createQueue(Constants.commandlineAddress, Constants.commandlineAddress, false);
+ messageBusSession.deleteQueue(Constants.COMMAND_LINE_ADDRESS);
+ messageBusSession.createQueue(Constants.ADDRESS, Constants.ADDRESS, false);
+ messageBusSession.createQueue(Constants.COMMAND_LINE_ADDRESS, Constants.COMMAND_LINE_ADDRESS, false);
- commandlineProducer = messageBusSession.createProducer(Constants.commandlineAddress);
+ commandlineProducer = messageBusSession.createProducer(Constants.COMMAND_LINE_ADDRESS);
- commandlineConsumer = messageBusSession.createConsumer(Constants.commandlineAddress, String.format("receiver = '%s'", "iofog.commandline.command"));
+ commandlineConsumer = messageBusSession.createConsumer(Constants.COMMAND_LINE_ADDRESS, String.format("receiver = '%s'", "iofog.commandline.command"));
commandlineConsumer.setMessageHandler(new CommandLineHandler());
messageBusSession.start();
}
@@ -153,7 +153,7 @@ void createCosumer(String name) throws Exception {
if (consumers == null)
consumers = new ConcurrentHashMap<>();
- ClientConsumer consumer = messageBusSession.createConsumer(Constants.address, String.format("receiver = '%s'", name));
+ ClientConsumer consumer = messageBusSession.createConsumer(Constants.ADDRESS, String.format("receiver = '%s'", name));
consumers.put(name, consumer);
}
@@ -193,7 +193,7 @@ void removeConsumer(String name) {
void createProducer(String name) throws Exception {
if (producers == null)
producers = new ConcurrentHashMap<>();
- ClientProducer producer = messageBusSession.createProducer(Constants.address);
+ ClientProducer producer = messageBusSession.createProducer(Constants.ADDRESS);
producers.put(name, producer);
}
@@ -276,6 +276,6 @@ void setMemoryLimit() {
addressSettings.setMaxSizeBytes(memoryLimit);
addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.DROP);
- server.getAddressSettingsRepository().addMatch(Constants.address, addressSettings);
+ server.getAddressSettingsRepository().addMatch(Constants.ADDRESS, addressSettings);
}
}
diff --git a/daemon/src/org/eclipse/iofog/utils/Constants.java b/daemon/src/org/eclipse/iofog/utils/Constants.java
index e08ac78e..b83d33b6 100755
--- a/daemon/src/org/eclipse/iofog/utils/Constants.java
+++ b/daemon/src/org/eclipse/iofog/utils/Constants.java
@@ -18,54 +18,92 @@
/**
* holds IOFog constants
- *
- * @author saeid
*
+ * @author saeid
*/
public class Constants {
- public enum ModulesStatus {
- STARTING, RUNNING, STOPPED
- }
-
- public enum DockerStatus {
- NOT_PRESENT, RUNNING, STOPPED
- }
-
- public enum LinkStatus {
- FAILED_VERIFICATION, FAILED_LOGIN, CONNECTED
- }
-
- public enum ControllerStatus {
- NOT_PROVISIONED, BROKEN, OK
- }
-
- public static final String VERSION = "1.03";
-
- public static final int NUMBER_OF_MODULES = 7;
-
- public static final int RESOURCE_CONSUMPTION_MANAGER = 0;
- public static final int PROCESS_MANAGER = 1;
- public static final int STATUS_REPORTER = 2;
- public static final int LOCAL_API = 3;
- public static final int MESSAGE_BUS = 4;
- public static final int FIELD_AGENT = 5;
- public static final int RESOURCE_MANAGER = 6;
-
- public static PrintStream systemOut;
-
- public static final String address = "iofog.message_bus";
- public static final String commandlineAddress = "iofog.commandline";
-
- public static final int KiB = 1024;
- public static final int MiB = KiB * KiB;
- public static final int GiB = KiB * KiB * KiB;
-
-
- public static final String SNAP = System.getenv("SNAP") != null ? System.getenv("SNAP") : "";
- public static final String SNAP_COMMON = System.getenv("SNAP_COMMON") != null ? System.getenv("SNAP_COMMON") : "";
- public static final String WINDOWS_IOFOG_PATH = System.getenv("IOFOG_PATH") != null ?
- System.getenv("IOFOG_PATH") + "config.xml" : "./config.xml";
- public static final String VAR_RUN = SystemUtils.IS_OS_WINDOWS ? SNAP_COMMON + "./var/run/iofog-agent" : SNAP_COMMON + "/var/run/iofog-agent";
- public static final String CONFIG_DIR = SystemUtils.IS_OS_WINDOWS ? WINDOWS_IOFOG_PATH : SNAP_COMMON + "/etc/iofog-agent/config.xml";
-}
+ public enum ModulesStatus {
+ STARTING, RUNNING, STOPPED
+ }
+
+ public enum DockerStatus {
+ NOT_PRESENT, RUNNING, STOPPED
+ }
+
+ public enum LinkStatus {
+ FAILED_VERIFICATION, FAILED_LOGIN, CONNECTED
+ }
+
+ public enum ControllerStatus {
+ NOT_PROVISIONED, BROKEN, OK
+ }
+
+ public enum ConfigSwitcherState {
+ DEFAULT(new String[]{"default", "def"}),
+ DEVELOPMENT(new String[]{"development", "dev"}),
+ PRODUCTION(new String[]{"production", "prod"});
+
+ ConfigSwitcherState(String[] aliases) {
+ this.aliases = aliases;
+ }
+
+ public static ConfigSwitcherState parse(String stringState) throws IllegalArgumentException {
+ for (ConfigSwitcherState switcherState : ConfigSwitcherState.values()) {
+ for (String alias : switcherState.aliases) {
+ if (alias.equalsIgnoreCase(stringState)) {
+ return switcherState;
+ }
+ }
+ }
+
+ throw new IllegalArgumentException("Invalid switcher state");
+ }
+
+ private String[] aliases;
+
+ public String fullValue() {
+ return aliases[0];
+ }
+ }
+
+ public static final String VERSION = "1.0.4";
+
+ public static final int NUMBER_OF_MODULES = 7;
+
+ public static final int RESOURCE_CONSUMPTION_MANAGER = 0;
+ public static final int PROCESS_MANAGER = 1;
+ public static final int STATUS_REPORTER = 2;
+ public static final int LOCAL_API = 3;
+ public static final int MESSAGE_BUS = 4;
+ public static final int FIELD_AGENT = 5;
+ public static final int RESOURCE_MANAGER = 6;
+
+ public static PrintStream systemOut;
+
+ public static final String ADDRESS = "iofog.message_bus";
+ public static final String COMMAND_LINE_ADDRESS = "iofog.commandline";
+
+ public static final int KiB = 1024;
+ public static final int MiB = KiB * KiB;
+ public static final int GiB = KiB * KiB * KiB;
+
+
+ public static final String SNAP = System.getenv("SNAP") != null ?
+ System.getenv("SNAP") : "";
+ public static final String SNAP_COMMON = System.getenv("SNAP_COMMON") != null ?
+ System.getenv("SNAP_COMMON") : "";
+ private static final String WINDOWS_IOFOG_PATH = System.getenv("IOFOG_PATH") != null ?
+ System.getenv("IOFOG_PATH") : "./";
+ public static final String VAR_RUN = SystemUtils.IS_OS_WINDOWS ?
+ SNAP_COMMON + "./var/run/iofog-agent" : SNAP_COMMON + "/var/run/iofog-agent";
+ private static final String CONFIG_DIR = SystemUtils.IS_OS_WINDOWS ?
+ WINDOWS_IOFOG_PATH : SNAP_COMMON + "/etc/iofog-agent/";
+ public static final String DEFAULT_CONFIG_PATH = CONFIG_DIR + "config.xml";
+ public static final String DEVELOPMENT_CONFIG_PATH = CONFIG_DIR + "config-development.xml";
+ public static final String PRODUCTION_CONFIG_PATH = CONFIG_DIR + "config-production.xml";
+ public static final String CONFIG_SWITCHER_PATH = CONFIG_DIR + "config-switcher.xml";
+ public static final String SWITCHER_ELEMENT = "switcher";
+ public static final String SWITCHER_NODE = "current_config";
+ public static final String OS_GROUP = "iofog-agent";
+}
\ No newline at end of file
diff --git a/daemon/src/org/eclipse/iofog/utils/Orchestrator.java b/daemon/src/org/eclipse/iofog/utils/Orchestrator.java
index ba6969b9..c5395b0f 100644
--- a/daemon/src/org/eclipse/iofog/utils/Orchestrator.java
+++ b/daemon/src/org/eclipse/iofog/utils/Orchestrator.java
@@ -78,7 +78,7 @@ public Orchestrator() {
public boolean ping() throws Exception {
try {
JsonObject result = getJSON(controllerUrl + "status");
- return result.getString("status").equals("ok");
+ return result.getString("status").equals("online");
} catch (Exception exp) {
logWarning(MODULE_NAME, exp.getMessage());
throw exp;
diff --git a/daemon/src/org/eclipse/iofog/utils/configuration/Configuration.java b/daemon/src/org/eclipse/iofog/utils/configuration/Configuration.java
index 714ce7b7..d2e54f1a 100644
--- a/daemon/src/org/eclipse/iofog/utils/configuration/Configuration.java
+++ b/daemon/src/org/eclipse/iofog/utils/configuration/Configuration.java
@@ -21,6 +21,8 @@
import org.eclipse.iofog.network.IOFogNetworkInterface;
import org.eclipse.iofog.process_manager.ProcessManager;
import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManager;
+import org.eclipse.iofog.supervisor.Supervisor;
+import org.eclipse.iofog.utils.Constants;
import org.eclipse.iofog.utils.device_info.ArchitectureType;
import org.eclipse.iofog.utils.logging.LoggingService;
import org.w3c.dom.Document;
@@ -48,8 +50,7 @@
import static org.apache.commons.lang.StringUtils.*;
import static org.eclipse.iofog.command_line.CommandLineConfigParam.*;
import static org.eclipse.iofog.utils.CmdProperties.*;
-import static org.eclipse.iofog.utils.Constants.CONFIG_DIR;
-import static org.eclipse.iofog.utils.Constants.SNAP_COMMON;
+import static org.eclipse.iofog.utils.Constants.*;
import static org.eclipse.iofog.utils.logging.LoggingService.logInfo;
/**
@@ -59,885 +60,1016 @@
*/
public final class Configuration {
- private static final String MODULE_NAME = "Configuration";
-
- private static Element configElement;
- private static Document configFile;
-//Directly configurable params
- private static String accessToken;
- private static String iofogUuid;
- private static String controllerUrl;
- private static String controllerCert;
- private static String networkInterface;
- private static String dockerUrl;
- private static float diskLimit;
- private static float memoryLimit;
- private static String diskDirectory;
- private static float cpuLimit;
- private static float logDiskLimit;
- private static String logDiskDirectory;
- private static int logFileCount;
- private static int statusFrequency;
- private static int changeFrequency;
- private static int deviceScanFrequency;
- private static int postDiagnosticsFreq;
- private static boolean watchdogEnabled;
- private static String gpsCoordinates;
- private static GpsMode gpsMode;
- private static ArchitectureType fogType;
- private static final Map defaultConfig;
- private static boolean developerMode;
-
- public static boolean debugging = false;
-
-//Automatic configurable params
- private static int statusReportFreqSeconds;
- private static int pingControllerFreqSeconds;
- private static int speedCalculationFreqMinutes;
- private static int monitorContainersStatusFreqSeconds;
- private static int monitorRegistriesStatusFreqSeconds;
- private static long getUsageDataFreqSeconds;
- private static String dockerApiVersion;
- private static int setSystemTimeFreqSeconds;
- private static int monitorSshTunnelStatusFreqSeconds;
-
- private static void updateAutomaticConfigParams() {
- switch (fogType) {
- case ARM:
- statusReportFreqSeconds = 10;
- pingControllerFreqSeconds = 60;
- speedCalculationFreqMinutes = 1;
- monitorContainersStatusFreqSeconds = 30;
- monitorRegistriesStatusFreqSeconds = 120;
- getUsageDataFreqSeconds = 20;
- dockerApiVersion = "1.23";
- setSystemTimeFreqSeconds = 60;
- monitorSshTunnelStatusFreqSeconds = 30;
- break;
- case INTEL_AMD:
- statusReportFreqSeconds = 5;
- pingControllerFreqSeconds = 60;
- speedCalculationFreqMinutes = 1;
- monitorContainersStatusFreqSeconds = 10;
- monitorRegistriesStatusFreqSeconds = 60;
- getUsageDataFreqSeconds = 5;
- dockerApiVersion = "1.23";
- setSystemTimeFreqSeconds = 60;
- monitorSshTunnelStatusFreqSeconds = 10;
- break;
- }
- }
-
- public static int getStatusReportFreqSeconds() {
- return statusReportFreqSeconds;
- }
-
- public static int getPingControllerFreqSeconds() {
- return pingControllerFreqSeconds;
- }
-
- public static int getSpeedCalculationFreqMinutes() {
- return speedCalculationFreqMinutes;
- }
-
- public static int getMonitorSshTunnelStatusFreqSeconds() {
- return monitorSshTunnelStatusFreqSeconds;
- }
-
- public static int getMonitorContainersStatusFreqSeconds() {
- return monitorContainersStatusFreqSeconds;
- }
-
- public static int getMonitorRegistriesStatusFreqSeconds() {
- return monitorRegistriesStatusFreqSeconds;
- }
-
- public static long getGetUsageDataFreqSeconds() {
- return getUsageDataFreqSeconds;
- }
-
- public static String getDockerApiVersion() {
- return dockerApiVersion;
- }
-
- public static int getSetSystemTimeFreqSeconds() {
- return setSystemTimeFreqSeconds;
- }
-
- static {
- defaultConfig = new HashMap<>();
- stream(values()).forEach(cmdParam -> defaultConfig.put(cmdParam.getCommandName(), cmdParam.getDefaultValue()));
- }
-
- public static boolean isWatchdogEnabled() {
- return watchdogEnabled;
- }
-
- public static void setWatchdogEnabled(boolean watchdogEnabled) {
- Configuration.watchdogEnabled = watchdogEnabled;
- }
-
- public static int getStatusFrequency() {
- return statusFrequency;
- }
-
- public static void setStatusFrequency(int statusFrequency) {
- Configuration.statusFrequency = statusFrequency;
- }
-
- public static int getChangeFrequency() {
- return changeFrequency;
- }
-
- public static void setChangeFrequency(int changeFrequency) {
- Configuration.changeFrequency = changeFrequency;
- }
-
- public static int getDeviceScanFrequency() {
- return deviceScanFrequency;
- }
-
- public static void setDeviceScanFrequency(int deviceScanFrequency) {
- Configuration.deviceScanFrequency = deviceScanFrequency;
- }
-
- public static String getGpsCoordinates() {
- return gpsCoordinates;
- }
-
- public static void setGpsCoordinates(String gpsCoordinates) {
- Configuration.gpsCoordinates = gpsCoordinates;
- }
-
- public static GpsMode getGpsMode() {
- return gpsMode;
- }
-
- public static void setGpsMode(GpsMode gpsMode) {
- Configuration.gpsMode = gpsMode;
- }
-
- public static void resetToDefault() throws Exception {
- setConfig(defaultConfig, true);
- }
-
- public static int getPostDiagnosticsFreq() {
- return postDiagnosticsFreq;
- }
-
- public static void setPostDiagnosticsFreq(int postDiagnosticsFreq) {
- Configuration.postDiagnosticsFreq = postDiagnosticsFreq;
- }
-
- public static ArchitectureType getFogType() {
- return fogType;
- }
-
- public static void setFogType(ArchitectureType fogType) {
- Configuration.fogType = fogType;
- }
-
- public static boolean isDeveloperMode() {
- return developerMode;
- }
-
- public static void setDeveloperMode(boolean developerMode) {
- Configuration.developerMode = developerMode;
- }
-
- /**
- * return XML node value
- *
- * @param param - node name
- * @return node value
- * @throws ConfigurationItemException
- */
- private static String getNode(CommandLineConfigParam param) {
-
- Supplier nodeReader = () -> {
- String res = null;
- try {
- res = getFirstNodeByTagName(param.getXmlTag()).getTextContent();
- } catch (Exception e) {
- System.out.println("[" + MODULE_NAME + "] <" + param.getXmlTag() + "> "
- + " item not found or defined more than once. Default value - " + param.getDefaultValue() + " will be used");
- }
- return res;
- };
- return Optional.ofNullable(nodeReader.get()).
- orElseGet(param::getDefaultValue);
- }
-
- /**
- * sets XML node value
- *
- * @param param - node param
- * @param content - node value
- * @throws ConfigurationItemException
- */
- private static void setNode(CommandLineConfigParam param, String content) throws ConfigurationItemException {
- createNodeIfNotExists(param.getXmlTag());
- getFirstNodeByTagName(param.getXmlTag()).setTextContent(content);
- }
-
- private static void createNodeIfNotExists(String name) {
- NodeList nodes = configElement.getElementsByTagName(name);
- if (nodes.getLength() == 0) {
- configElement.appendChild(configFile.createElement(name));
- }
- }
-
- /**
- * return first XML node from list of nodes found based on provided tag name
- *
- * @param name - node name
- * @return Node object
- * @throws ConfigurationItemException
- */
- private static Node getFirstNodeByTagName(String name) throws ConfigurationItemException {
- NodeList nodes = configFile.getElementsByTagName(name);
-
- if (nodes.getLength() != 1) {
- throw new ConfigurationItemException("<" + name + "> item not found or defined more than once");
- }
-
- return nodes.item(0);
- }
-
- public static HashMap getOldNodeValuesForParameters(Set parameters) throws ConfigurationItemException {
-
- HashMap result = new HashMap<>();
-
- for (String option : parameters) {
- CommandLineConfigParam cmdOption = getCommandByName(option)
- .orElseThrow(() -> new ConfigurationItemException("Invalid parameter -" + option));
- result.put(cmdOption.getCommandName(), getNode(cmdOption));
- }
-
- return result;
- }
-
- /**
- * saves configuration data to config.xml
- * and informs other modules
- *
- * @throws Exception
- */
- public static void saveConfigUpdates() throws Exception {
- FieldAgent.getInstance().instanceConfigUpdated();
- ProcessManager.getInstance().instanceConfigUpdated();
- ResourceConsumptionManager.getInstance().instanceConfigUpdated();
- LoggingService.instanceConfigUpdated();
- MessageBus.getInstance().instanceConfigUpdated();
-
- updateConfigFile();
- }
-
- /**
- * saves configuration data to config.xml
- *
- * @throws Exception
- */
- private static void updateConfigFile() throws Exception {
- Transformer transformer = TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- StreamResult result = new StreamResult(new File(CONFIG_DIR));
- DOMSource source = new DOMSource(configFile);
- transformer.transform(source, result);
- }
-
- /**
- * sets configuration base on commandline parameters
- *
- * @param commandLineMap - map of config parameters
- * @throws Exception
- */
- public static HashMap setConfig(Map commandLineMap, boolean defaults) throws Exception {
-
- HashMap messageMap = new HashMap<>();
-
- for (Map.Entry command : commandLineMap.entrySet()) {
- String option = command.getKey();
- CommandLineConfigParam cmdOption = CommandLineConfigParam.getCommandByName(option).get();
- String value = command.getValue().toString();
-
- if (value.startsWith("+")) value = value.substring(1);
-
- if (isBlank(option) || isBlank(value)) {
- if (!option.equals(CONTROLLER_CERT.getCommandName())) {
- messageMap.put("Parameter error", "Command or value is invalid");
- break;
- }
- }
-
- int intValue;
- switch (cmdOption) {
- case DISK_CONSUMPTION_LIMIT:
- try {
- Float.parseFloat(value);
- } catch (Exception e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
-
- if (Float.parseFloat(value) < 1 || Float.parseFloat(value) > 1048576) {
- messageMap.put(option, "Disk limit range must be 1 to 1048576 GB");
- break;
- }
- setDiskLimit(Float.parseFloat(value));
- setNode(DISK_CONSUMPTION_LIMIT, value);
- break;
-
- case DISK_DIRECTORY:
- value = addSeparator(value);
- setDiskDirectory(value);
- setNode(DISK_DIRECTORY, value);
- break;
- case MEMORY_CONSUMPTION_LIMIT:
- try {
- Float.parseFloat(value);
- } catch (Exception e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (Float.parseFloat(value) < 128 || Float.parseFloat(value) > 1048576) {
- messageMap.put(option, "Memory limit range must be 128 to 1048576 MB");
- break;
- }
- setMemoryLimit(Float.parseFloat(value));
- setNode(MEMORY_CONSUMPTION_LIMIT, value);
- break;
- case PROCESSOR_CONSUMPTION_LIMIT:
- try {
- Float.parseFloat(value);
- } catch (Exception e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (Float.parseFloat(value) < 5 || Float.parseFloat(value) > 100) {
- messageMap.put(option, "CPU limit range must be 5% to 100%");
- break;
- }
- setCpuLimit(Float.parseFloat(value));
- setNode(PROCESSOR_CONSUMPTION_LIMIT, value);
- break;
- case CONTROLLER_URL:
- setNode(CONTROLLER_URL, value);
- setControllerUrl(value);
- break;
- case CONTROLLER_CERT:
- setNode(CONTROLLER_CERT, value);
- setControllerCert(value);
- break;
- case DOCKER_URL:
- setNode(DOCKER_URL, value);
- setDockerUrl(value);
- break;
- case NETWORK_INTERFACE:
- if (defaults || isValidNetworkInterface(value.trim())) {
- setNode(NETWORK_INTERFACE, value);
- setNetworkInterface(value);
- } else {
- messageMap.put(option, "Invalid network interface");
- break;
- }
- break;
- case LOG_DISK_CONSUMPTION_LIMIT:
- try {
- Float.parseFloat(value);
- } catch (Exception e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (Float.parseFloat(value) < 0.5 || Float.parseFloat(value) > 1024) {
- messageMap.put(option, "Log disk limit range must be 0.5 to 1024 GB");
- break;
- }
- setNode(LOG_DISK_CONSUMPTION_LIMIT, value);
- setLogDiskLimit(Float.parseFloat(value));
- break;
- case LOG_DISK_DIRECTORY:
- value = addSeparator(value);
- setNode(LOG_DISK_DIRECTORY, value);
- setLogDiskDirectory(value);
- break;
- case LOG_FILE_COUNT:
- try {
- intValue = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (intValue < 1 || intValue > 100) {
- messageMap.put(option, "Log file count range must be 1 to 100");
- break;
- }
- setNode(LOG_FILE_COUNT, value);
- setLogFileCount(Integer.parseInt(value));
- break;
- case STATUS_FREQUENCY:
- try {
- intValue = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (intValue < 1) {
- messageMap.put(option, "Status update frequency must be greater than 1");
- break;
- }
- setNode(STATUS_FREQUENCY, value);
- setStatusFrequency(Integer.parseInt(value));
- break;
- case CHANGE_FREQUENCY:
- try {
- intValue = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (intValue < 1) {
- messageMap.put(option, "Get changes frequency must be greater than 1");
- break;
- }
- setNode(CHANGE_FREQUENCY, value);
- setChangeFrequency(Integer.parseInt(value));
- break;
- case DEVICE_SCAN_FREQUENCY:
- try {
- intValue = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (intValue < 1) {
- messageMap.put(option, "Get scan devices frequency must be greater than 1");
- break;
- }
- setNode(DEVICE_SCAN_FREQUENCY, value);
- setDeviceScanFrequency(Integer.parseInt(value));
- break;
- case POST_DIAGNOSTICS_FREQ:
- try {
- intValue = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- messageMap.put(option, "Option -" + option + " has invalid value: " + value);
- break;
- }
- if (intValue < 1) {
- messageMap.put(option, "Post diagnostics frequency must be greater than 1");
- break;
- }
- setNode(POST_DIAGNOSTICS_FREQ, value);
- setPostDiagnosticsFreq(Integer.parseInt(value));
- break;
- case WATCHDOG_ENABLED:
- setNode(WATCHDOG_ENABLED, value);
- setWatchdogEnabled(!value.equals("off"));
- break;
- case GPS_COORDINATES:
- configureGps(value);
- writeGpsToConfigFile();
- break;
- case FOG_TYPE:
- configureFogType(value);
- setNode(FOG_TYPE, value);
- break;
- case DEV_MODE:
- setNode(DEV_MODE, value);
- setDeveloperMode(!value.equals("off"));
- break;
- default:
- throw new ConfigurationItemException("Invalid parameter -" + option);
- }
- }
- saveConfigUpdates();
-
- return messageMap;
- }
-
- /**
- * Configures fogType.
- *
- * @param fogTypeCommand could be "auto" or string that matches one of the {@link ArchitectureType} patterns
- * @throws ConfigurationItemException if {@link ArchitectureType} undefined
- */
- private static void configureFogType(String fogTypeCommand) throws ConfigurationItemException {
- ArchitectureType newFogType = ArchitectureType.UNDEFINED;
- switch (fogTypeCommand) {
- case "auto": {
- newFogType = ArchitectureType.getArchTypeByArchName(System.getProperty("os.arch"));
- break;
- }
- case "intel_amd": {
- newFogType = ArchitectureType.INTEL_AMD;
- break;
- }
- case "arm": {
- newFogType = ArchitectureType.ARM;
- break;
- }
- }
-
- if (newFogType == ArchitectureType.UNDEFINED) {
- throw new ConfigurationItemException("Couldn't autodetect fogType or unknown fogType type was set.");
- }
-
- setFogType(newFogType);
- updateAutomaticConfigParams();
- }
-
- /**
- * Configures GPS coordinates and mode in config file
- *
- * @param gpsCoordinatesCommand coordinates special command or lat,lon string (prefer using DD GPS format)
- * @throws ConfigurationItemException
- */
- private static void configureGps(String gpsCoordinatesCommand) throws ConfigurationItemException {
- String gpsCoordinates;
- GpsMode currentMode;
-
- if (GpsMode.AUTO.name().toLowerCase().equals(gpsCoordinatesCommand)) {
- gpsCoordinates = GpsWebHandler.getGpsCoordinatesByExternalIp();
- currentMode = GpsMode.AUTO;
- } else if (GpsMode.OFF.name().toLowerCase().equals(gpsCoordinatesCommand)) {
- gpsCoordinates = "";
- currentMode = GpsMode.OFF;
- } else {
- gpsCoordinates = gpsCoordinatesCommand;
- currentMode = GpsMode.MANUAL;
- }
-
- setGpsDataIfValid(currentMode, gpsCoordinates);
- }
-
- public static void setGpsDataIfValid(GpsMode mode, String gpsCoordinates) throws ConfigurationItemException {
- if (!isValidCoordinates(gpsCoordinates)) {
- throw new ConfigurationItemException("Incorrect GPS coordinates value: " + gpsCoordinates + "\n"
- + "Correct format is (GPS DD format)");
- }
-
- setGpsCoordinates(gpsCoordinates.trim());
- setGpsMode(mode);
- }
-
- /**
- * Writes GPS coordinates and GPS mode to config file
- *
- * @throws ConfigurationItemException
- */
- public static void writeGpsToConfigFile() throws ConfigurationItemException {
- if (gpsMode == GpsMode.MANUAL) {
- setNode(GPS_COORDINATES, gpsCoordinates);
- } else {
- setNode(GPS_COORDINATES, gpsMode.name().toLowerCase());
- }
- }
-
- /**
- * Checks is string a valid DD GPS coordinates
- *
- * @param gpsCoordinates
- * @return
- */
- private static boolean isValidCoordinates(String gpsCoordinates) {
-
- boolean isValid = true;
-
- String fpRegex = "[+-]?[0-9]+(.?[0-9]+)?,?" +
- "[+-]?[0-9]+(.?[0-9]+)?";
-
- if (Pattern.matches(fpRegex, gpsCoordinates)) {
-
- String[] latLon = gpsCoordinates.split(",");
- double lat = Double.parseDouble(latLon[0]);
- double lon = Double.parseDouble(latLon[1]);
-
- if (lat > 90 || lat < -90 || lon > 180 || lon < -180) {
- isValid = false;
- }
- } else {
- isValid = gpsCoordinates.isEmpty();
- }
-
- return isValid;
- }
-
- /**
- * checks if given network interface is valid
- *
- * @param eth - network interface
- * @return
- */
- private static boolean isValidNetworkInterface(String eth) {
- if (SystemUtils.IS_OS_WINDOWS) { // any name could be used for network interface on Win
- return true;
- }
-
- try {
- if (CommandLineConfigParam.NETWORK_INTERFACE.getDefaultValue().equals(eth)) {
- return true;
- }
- Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
- for (NetworkInterface networkInterface : list(networkInterfaces)) {
- if (networkInterface.getName().equalsIgnoreCase(eth))
- return true;
- }
- } catch (Exception e) {
- logInfo(MODULE_NAME, "Error validating network interface : " + e.getMessage());
- }
- return false;
- }
-
- /**
- * adds file separator to end of directory names, if not exists
- *
- * @param value - name of directory
- * @return directory containing file separator at the end
- */
- private static String addSeparator(String value) {
- if (value.charAt(value.length() - 1) == separatorChar)
- return value;
- else
- return value + separatorChar;
- }
-
-
- /**
- * loads configuration from config.xml file
- *
- * @throws Exception
- */
- public static void loadConfig() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
-
- configFile = builder.parse(CONFIG_DIR);
- configFile.getDocumentElement().normalize();
-
- configElement = (Element) getFirstNodeByTagName("config");
-
- setIofogUuid(getNode(IOFOG_UUID));
- setAccessToken(getNode(ACCESS_TOKEN));
- setControllerUrl(getNode(CONTROLLER_URL));
- setControllerCert(getNode(CONTROLLER_CERT));
- setNetworkInterface(getNode(NETWORK_INTERFACE));
- setDockerUrl(getNode(DOCKER_URL));
- setDiskLimit(Float.parseFloat(getNode(DISK_CONSUMPTION_LIMIT)));
- setDiskDirectory(getNode(DISK_DIRECTORY));
- setMemoryLimit(Float.parseFloat(getNode(MEMORY_CONSUMPTION_LIMIT)));
- setCpuLimit(Float.parseFloat(getNode(PROCESSOR_CONSUMPTION_LIMIT)));
- setLogDiskDirectory(getNode(LOG_DISK_DIRECTORY));
- setLogDiskLimit(Float.parseFloat(getNode(LOG_DISK_CONSUMPTION_LIMIT)));
- setLogFileCount(Integer.parseInt(getNode(LOG_FILE_COUNT)));
- configureGps(getNode(GPS_COORDINATES));
- setChangeFrequency(Integer.parseInt(getNode(CHANGE_FREQUENCY)));
- setDeviceScanFrequency(Integer.parseInt(getNode(DEVICE_SCAN_FREQUENCY)));
- setStatusFrequency(Integer.parseInt(getNode(STATUS_FREQUENCY)));
- setPostDiagnosticsFreq(Integer.parseInt(getNode(POST_DIAGNOSTICS_FREQ)));
- setWatchdogEnabled(!getNode(WATCHDOG_ENABLED).equals("off"));
- configureFogType(getNode(FOG_TYPE));
- setDeveloperMode(!getNode(DEV_MODE).equals("off"));
-
- }
-
- // this code will be triggered in case of iofog updated (not newly installed) and add new option for config
- private static void createConfigProperty(CommandLineConfigParam cmdParam) throws Exception {
- // TODO: add appropriate handling of case when 0 nodes found or multiple before adding new property to file
- Element el = configFile.createElement(cmdParam.getXmlTag());
- el.appendChild(configFile.createTextNode(cmdParam.getDefaultValue()));
- configElement.appendChild(el);
-
- DOMSource source = new DOMSource(configFile);
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- Transformer transformer = transformerFactory.newTransformer();
- StreamResult result = new StreamResult(CONFIG_DIR);
- transformer.transform(source, result);
- }
-
- public static String getAccessToken() {
- return accessToken;
- }
-
- public static String getControllerUrl() {
- return controllerUrl;
- }
-
- public static String getControllerCert() {
- return controllerCert;
- }
-
- public static String getNetworkInterface() {
- return networkInterface;
- }
-
- public static String getDockerUrl() {
- return dockerUrl;
- }
-
- public static float getDiskLimit() {
- return diskLimit;
- }
-
- public static float getMemoryLimit() {
- return memoryLimit;
- }
-
- public static String getDiskDirectory() {
- return diskDirectory;
- }
-
- public static float getCpuLimit() {
- return cpuLimit;
- }
-
- public static String getIofogUuid() {
- return iofogUuid;
- }
-
- public static int getLogFileCount() {
- return logFileCount;
- }
-
- public static float getLogDiskLimit() {
- return logDiskLimit;
- }
-
- public static String getLogDiskDirectory() {
- return logDiskDirectory;
- }
-
- public static void setLogDiskDirectory(String logDiskDirectory) {
- if (logDiskDirectory.charAt(0) != separatorChar)
- logDiskDirectory = separatorChar + logDiskDirectory;
- if (logDiskDirectory.charAt(logDiskDirectory.length() - 1) != separatorChar)
- logDiskDirectory += separatorChar;
- Configuration.logDiskDirectory = SNAP_COMMON + logDiskDirectory;
- }
-
- public static void setAccessToken(String accessToken) throws ConfigurationItemException {
- setNode(ACCESS_TOKEN, accessToken);
- Configuration.accessToken = accessToken;
- }
-
- public static void setIofogUuid(String iofogUuid) throws ConfigurationItemException {
- setNode(IOFOG_UUID, iofogUuid);
- Configuration.iofogUuid = iofogUuid;
- }
-
- public static void setControllerUrl(String controllerUrl) {
- if (controllerUrl != null && controllerUrl.length() > 0 && controllerUrl.charAt(controllerUrl.length() - 1) != '/')
- controllerUrl += '/';
- Configuration.controllerUrl = controllerUrl;
- }
-
- public static void setControllerCert(String controllerCert) {
- Configuration.controllerCert = SNAP_COMMON + controllerCert;
- }
-
- public static void setNetworkInterface(String networkInterface) {
- Configuration.networkInterface = networkInterface;
- }
-
- public static void setDockerUrl(String dockerUrl) {
- Configuration.dockerUrl = dockerUrl;
- }
-
- public static void setDiskLimit(float diskLimit) {
- Configuration.diskLimit = diskLimit;
- }
-
- public static void setMemoryLimit(float memoryLimit) {
- Configuration.memoryLimit = memoryLimit;
- }
-
- public static void setDiskDirectory(String diskDirectory) {
- if (diskDirectory.charAt(0) != separatorChar)
- diskDirectory = separatorChar + diskDirectory;
- if (diskDirectory.charAt(diskDirectory.length() - 1) != separatorChar)
- diskDirectory += separatorChar;
- Configuration.diskDirectory = SNAP_COMMON + diskDirectory;
- }
-
- public static void setCpuLimit(float cpuLimit) {
- Configuration.cpuLimit = cpuLimit;
- }
-
- public static void setLogDiskLimit(float logDiskLimit) {
- Configuration.logDiskLimit = logDiskLimit;
- }
-
- public static void setLogFileCount(int logFileCount) {
- Configuration.logFileCount = logFileCount;
- }
-
- /**
- * returns report for "info" commandline parameter
- *
- * @return info report
- */
- public static String getConfigReport() {
- String ipAddress = IOFogNetworkInterface.getCurrentIpAddress();
- String networkInterface = getNetworkInterfaceInfo();
- ipAddress = "".equals(ipAddress) ? "unable to retrieve ip address" : ipAddress;
-
- StringBuilder result = new StringBuilder();
- // iofog UUID
- result.append(buildReportLine(getIofogUuidMessage(), isNotBlank(iofogUuid) ? iofogUuid : "not provisioned"));
- //ip address
- result.append(buildReportLine(getIpAddressMessage(), ipAddress));
- // network interface
- result.append(buildReportLine(getConfigParamMessage(NETWORK_INTERFACE), networkInterface));
- // developer mode
- result.append(buildReportLine(getConfigParamMessage(DEV_MODE), (developerMode ? "on" : "off")));
- // controller url
- result.append(buildReportLine(getConfigParamMessage(CONTROLLER_URL), controllerUrl));
- // controller cert dir
- result.append(buildReportLine(getConfigParamMessage(CONTROLLER_CERT), controllerCert));
- // docker url
- result.append(buildReportLine(getConfigParamMessage(DOCKER_URL), dockerUrl));
- // disk usage limit
- result.append(buildReportLine(getConfigParamMessage(DISK_CONSUMPTION_LIMIT), format("%.2f GiB", diskLimit)));
- // disk directory
- result.append(buildReportLine(getConfigParamMessage(DISK_DIRECTORY), diskDirectory));
- // memory ram limit
- result.append(buildReportLine(getConfigParamMessage(MEMORY_CONSUMPTION_LIMIT), format("%.2f MiB", memoryLimit)));
- // cpu usage limit
- result.append(buildReportLine(getConfigParamMessage(PROCESSOR_CONSUMPTION_LIMIT), format("%.2f%%", cpuLimit)));
- // log disk limit
- result.append(buildReportLine(getConfigParamMessage(LOG_DISK_CONSUMPTION_LIMIT), format("%.2f GiB", logDiskLimit)));
- // log file directory
- result.append(buildReportLine(getConfigParamMessage(LOG_DISK_DIRECTORY), logDiskDirectory));
- // log files count
- result.append(buildReportLine(getConfigParamMessage(LOG_FILE_COUNT), format("%d", logFileCount)));
- // status update frequency
- result.append(buildReportLine(getConfigParamMessage(STATUS_FREQUENCY), format("%d", statusFrequency)));
- // status update frequency
- result.append(buildReportLine(getConfigParamMessage(CHANGE_FREQUENCY), format("%d", changeFrequency)));
- // scan devices frequency
- result.append(buildReportLine(getConfigParamMessage(DEVICE_SCAN_FREQUENCY), format("%d", deviceScanFrequency)));
- // post diagnostics frequency
- result.append(buildReportLine(getConfigParamMessage(POST_DIAGNOSTICS_FREQ), format("%d", postDiagnosticsFreq)));
- // log file directory
- result.append(buildReportLine(getConfigParamMessage(WATCHDOG_ENABLED), (watchdogEnabled ? "on" : "off")));
- // gps mode
- result.append(buildReportLine(getConfigParamMessage(GPS_MODE), gpsMode.name().toLowerCase()));
- // gps coordinates
- result.append(buildReportLine(getConfigParamMessage(GPS_COORDINATES), gpsCoordinates));
- //fog type
- result.append(buildReportLine(getConfigParamMessage(FOG_TYPE), fogType.name().toLowerCase()));
-
- return result.toString();
- }
-
- private static String buildReportLine(String messageDescription, String value) {
- return rightPad(messageDescription, 40, ' ') + " : " + value + "\\n";
- }
-
- private static String getNetworkInterfaceInfo() {
- return NETWORK_INTERFACE.getDefaultValue().equals(networkInterface) ?
- IOFogNetworkInterface.getNetworkInterface() + "(" + NETWORK_INTERFACE.getDefaultValue() + ")" :
- networkInterface;
- }
-
+ private static final String MODULE_NAME = "Configuration";
+
+ private static Element configElement;
+ private static Document configFile;
+ private static Element configSwitcherElement;
+ private static Document configSwitcherFile;
+ private static ConfigSwitcherState currentSwitcherState;
+ //Directly configurable params
+ private static String accessToken;
+ private static String iofogUuid;
+ private static String controllerUrl;
+ private static String controllerCert;
+ private static String networkInterface;
+ private static String dockerUrl;
+ private static float diskLimit;
+ private static float memoryLimit;
+ private static String diskDirectory;
+ private static float cpuLimit;
+ private static float logDiskLimit;
+ private static String logDiskDirectory;
+ private static int logFileCount;
+ private static int statusFrequency;
+ private static int changeFrequency;
+ private static int deviceScanFrequency;
+ private static int postDiagnosticsFreq;
+ private static boolean watchdogEnabled;
+ private static String gpsCoordinates;
+ private static GpsMode gpsMode;
+ private static ArchitectureType fogType;
+ private static final Map defaultConfig;
+ private static boolean developerMode;
+
+ public static boolean debugging = false;
+
+ //Automatic configurable params
+ private static int statusReportFreqSeconds;
+ private static int pingControllerFreqSeconds;
+ private static int speedCalculationFreqMinutes;
+ private static int monitorContainersStatusFreqSeconds;
+ private static int monitorRegistriesStatusFreqSeconds;
+ private static long getUsageDataFreqSeconds;
+ private static String dockerApiVersion;
+ private static int setSystemTimeFreqSeconds;
+ private static int monitorSshTunnelStatusFreqSeconds;
+
+ private static void updateAutomaticConfigParams() {
+ switch (fogType) {
+ case ARM:
+ statusReportFreqSeconds = 10;
+ pingControllerFreqSeconds = 60;
+ speedCalculationFreqMinutes = 1;
+ monitorContainersStatusFreqSeconds = 30;
+ monitorRegistriesStatusFreqSeconds = 120;
+ getUsageDataFreqSeconds = 20;
+ dockerApiVersion = "1.23";
+ setSystemTimeFreqSeconds = 60;
+ monitorSshTunnelStatusFreqSeconds = 30;
+ break;
+ case INTEL_AMD:
+ statusReportFreqSeconds = 5;
+ pingControllerFreqSeconds = 60;
+ speedCalculationFreqMinutes = 1;
+ monitorContainersStatusFreqSeconds = 10;
+ monitorRegistriesStatusFreqSeconds = 60;
+ getUsageDataFreqSeconds = 5;
+ dockerApiVersion = "1.23";
+ setSystemTimeFreqSeconds = 60;
+ monitorSshTunnelStatusFreqSeconds = 10;
+ break;
+ }
+ }
+
+ public static int getStatusReportFreqSeconds() {
+ return statusReportFreqSeconds;
+ }
+
+ public static int getPingControllerFreqSeconds() {
+ return pingControllerFreqSeconds;
+ }
+
+ public static int getSpeedCalculationFreqMinutes() {
+ return speedCalculationFreqMinutes;
+ }
+
+ public static int getMonitorSshTunnelStatusFreqSeconds() {
+ return monitorSshTunnelStatusFreqSeconds;
+ }
+
+ public static int getMonitorContainersStatusFreqSeconds() {
+ return monitorContainersStatusFreqSeconds;
+ }
+
+ public static int getMonitorRegistriesStatusFreqSeconds() {
+ return monitorRegistriesStatusFreqSeconds;
+ }
+
+ public static long getGetUsageDataFreqSeconds() {
+ return getUsageDataFreqSeconds;
+ }
+
+ public static String getDockerApiVersion() {
+ return dockerApiVersion;
+ }
+
+ public static int getSetSystemTimeFreqSeconds() {
+ return setSystemTimeFreqSeconds;
+ }
+
+ static {
+ defaultConfig = new HashMap<>();
+ stream(values()).forEach(cmdParam -> defaultConfig.put(cmdParam.getCommandName(), cmdParam.getDefaultValue()));
+ }
+
+ public static boolean isWatchdogEnabled() {
+ return watchdogEnabled;
+ }
+
+ public static void setWatchdogEnabled(boolean watchdogEnabled) {
+ Configuration.watchdogEnabled = watchdogEnabled;
+ }
+
+ public static int getStatusFrequency() {
+ return statusFrequency;
+ }
+
+ public static void setStatusFrequency(int statusFrequency) {
+ Configuration.statusFrequency = statusFrequency;
+ }
+
+ public static int getChangeFrequency() {
+ return changeFrequency;
+ }
+
+ public static void setChangeFrequency(int changeFrequency) {
+ Configuration.changeFrequency = changeFrequency;
+ }
+
+ public static int getDeviceScanFrequency() {
+ return deviceScanFrequency;
+ }
+
+ public static void setDeviceScanFrequency(int deviceScanFrequency) {
+ Configuration.deviceScanFrequency = deviceScanFrequency;
+ }
+
+ public static String getGpsCoordinates() {
+ return gpsCoordinates;
+ }
+
+ public static void setGpsCoordinates(String gpsCoordinates) {
+ Configuration.gpsCoordinates = gpsCoordinates;
+ }
+
+ public static GpsMode getGpsMode() {
+ return gpsMode;
+ }
+
+ public static void setGpsMode(GpsMode gpsMode) {
+ Configuration.gpsMode = gpsMode;
+ }
+
+ public static void resetToDefault() throws Exception {
+ setConfig(defaultConfig, true);
+ }
+
+ public static int getPostDiagnosticsFreq() {
+ return postDiagnosticsFreq;
+ }
+
+ public static void setPostDiagnosticsFreq(int postDiagnosticsFreq) {
+ Configuration.postDiagnosticsFreq = postDiagnosticsFreq;
+ }
+
+ public static ArchitectureType getFogType() {
+ return fogType;
+ }
+
+ public static void setFogType(ArchitectureType fogType) {
+ Configuration.fogType = fogType;
+ }
+
+ public static boolean isDeveloperMode() {
+ return developerMode;
+ }
+
+ public static void setDeveloperMode(boolean developerMode) {
+ Configuration.developerMode = developerMode;
+ }
+
+ /**
+ * return XML node value
+ *
+ * @param param - node name
+ * @return node value
+ * @throws ConfigurationItemException
+ */
+ private static String getNode(CommandLineConfigParam param, Document document) {
+
+ Supplier nodeReader = () -> {
+ String res = null;
+ try {
+ res = getFirstNodeByTagName(param.getXmlTag(), document).getTextContent();
+ } catch (Exception e) {
+ System.out.println("[" + MODULE_NAME + "] <" + param.getXmlTag() + "> "
+ + " item not found or defined more than once. Default value - " + param.getDefaultValue() + " will be used");
+ }
+ return res;
+ };
+ return Optional.ofNullable(nodeReader.get()).
+ orElseGet(param::getDefaultValue);
+ }
+
+ /**
+ * sets XML node value
+ *
+ * @param param - node param
+ * @param content - node value
+ * @throws ConfigurationItemException
+ */
+ private static void setNode(CommandLineConfigParam param, String content, Document document, Element node) throws ConfigurationItemException {
+ createNodeIfNotExists(param.getXmlTag(), document, node);
+ getFirstNodeByTagName(param.getXmlTag(), document).setTextContent(content);
+ }
+
+ private static void createNodeIfNotExists(String name, Document document, Element node) {
+ NodeList nodes = node.getElementsByTagName(name);
+ if (nodes.getLength() == 0) {
+ node.appendChild(document.createElement(name));
+ }
+ }
+
+ /**
+ * return first XML node from list of nodes found based on provided tag name
+ *
+ * @param name - node name
+ * @return Node object
+ * @throws ConfigurationItemException
+ */
+ private static Node getFirstNodeByTagName(String name, Document document) throws ConfigurationItemException {
+ NodeList nodes = document.getElementsByTagName(name);
+
+ if (nodes.getLength() != 1) {
+ throw new ConfigurationItemException("<" + name + "> item not found or defined more than once");
+ }
+
+ return nodes.item(0);
+ }
+
+ public static HashMap getOldNodeValuesForParameters(Set parameters, Document document) throws ConfigurationItemException {
+
+ HashMap result = new HashMap<>();
+
+ for (String option : parameters) {
+ CommandLineConfigParam cmdOption = getCommandByName(option)
+ .orElseThrow(() -> new ConfigurationItemException("Invalid parameter -" + option));
+ result.put(cmdOption.getCommandName(), getNode(cmdOption, document));
+ }
+
+ return result;
+ }
+
+ /**
+ * saves configuration data to config.xml
+ * and informs other modules
+ *
+ * @throws Exception
+ */
+ public static void saveConfigUpdates() throws Exception {
+ FieldAgent.getInstance().instanceConfigUpdated();
+ ProcessManager.getInstance().instanceConfigUpdated();
+ ResourceConsumptionManager.getInstance().instanceConfigUpdated();
+ LoggingService.instanceConfigUpdated();
+ MessageBus.getInstance().instanceConfigUpdated();
+
+ updateConfigFile(getCurrentConfigPath(), configFile);
+ }
+
+ /**
+ * saves configuration data to config.xml
+ *
+ * @throws Exception
+ */
+ private static void updateConfigFile(String filePath, Document newFile) throws Exception {
+ Transformer transformer = TransformerFactory.newInstance().newTransformer();
+ transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+ StreamResult result = new StreamResult(new File(filePath));
+ DOMSource source = new DOMSource(newFile);
+ transformer.transform(source, result);
+ }
+
+ /**
+ * sets configuration base on commandline parameters
+ *
+ * @param commandLineMap - map of config parameters
+ * @throws Exception
+ */
+ public static HashMap setConfig(Map commandLineMap, boolean defaults) throws Exception {
+
+ HashMap messageMap = new HashMap<>();
+
+ for (Map.Entry command : commandLineMap.entrySet()) {
+ String option = command.getKey();
+ CommandLineConfigParam cmdOption = CommandLineConfigParam.getCommandByName(option).get();
+ String value = command.getValue().toString();
+
+ if (value.startsWith("+")) value = value.substring(1);
+
+ if (isBlank(option) || isBlank(value)) {
+ if (!option.equals(CONTROLLER_CERT.getCommandName())) {
+ messageMap.put("Parameter error", "Command or value is invalid");
+ break;
+ }
+ }
+
+ int intValue;
+ switch (cmdOption) {
+ case DISK_CONSUMPTION_LIMIT:
+ try {
+ Float.parseFloat(value);
+ } catch (Exception e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+
+ if (Float.parseFloat(value) < 1 || Float.parseFloat(value) > 1048576) {
+ messageMap.put(option, "Disk limit range must be 1 to 1048576 GB");
+ break;
+ }
+ setDiskLimit(Float.parseFloat(value));
+ setNode(DISK_CONSUMPTION_LIMIT, value, configFile, configElement);
+ break;
+
+ case DISK_DIRECTORY:
+ value = addSeparator(value);
+ setDiskDirectory(value);
+ setNode(DISK_DIRECTORY, value, configFile, configElement);
+ break;
+ case MEMORY_CONSUMPTION_LIMIT:
+ try {
+ Float.parseFloat(value);
+ } catch (Exception e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (Float.parseFloat(value) < 128 || Float.parseFloat(value) > 1048576) {
+ messageMap.put(option, "Memory limit range must be 128 to 1048576 MB");
+ break;
+ }
+ setMemoryLimit(Float.parseFloat(value));
+ setNode(MEMORY_CONSUMPTION_LIMIT, value, configFile, configElement);
+ break;
+ case PROCESSOR_CONSUMPTION_LIMIT:
+ try {
+ Float.parseFloat(value);
+ } catch (Exception e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (Float.parseFloat(value) < 5 || Float.parseFloat(value) > 100) {
+ messageMap.put(option, "CPU limit range must be 5% to 100%");
+ break;
+ }
+ setCpuLimit(Float.parseFloat(value));
+ setNode(PROCESSOR_CONSUMPTION_LIMIT, value, configFile, configElement);
+ break;
+ case CONTROLLER_URL:
+ setNode(CONTROLLER_URL, value, configFile, configElement);
+ setControllerUrl(value);
+ break;
+ case CONTROLLER_CERT:
+ setNode(CONTROLLER_CERT, value, configFile, configElement);
+ setControllerCert(value);
+ break;
+ case DOCKER_URL:
+ setNode(DOCKER_URL, value, configFile, configElement);
+ setDockerUrl(value);
+ break;
+ case NETWORK_INTERFACE:
+ if (defaults || isValidNetworkInterface(value.trim())) {
+ setNode(NETWORK_INTERFACE, value, configFile, configElement);
+ setNetworkInterface(value);
+ } else {
+ messageMap.put(option, "Invalid network interface");
+ break;
+ }
+ break;
+ case LOG_DISK_CONSUMPTION_LIMIT:
+ try {
+ Float.parseFloat(value);
+ } catch (Exception e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (Float.parseFloat(value) < 0.5 || Float.parseFloat(value) > 1024) {
+ messageMap.put(option, "Log disk limit range must be 0.5 to 1024 GB");
+ break;
+ }
+ setNode(LOG_DISK_CONSUMPTION_LIMIT, value, configFile, configElement);
+ setLogDiskLimit(Float.parseFloat(value));
+ break;
+ case LOG_DISK_DIRECTORY:
+ value = addSeparator(value);
+ setNode(LOG_DISK_DIRECTORY, value, configFile, configElement);
+ setLogDiskDirectory(value);
+ break;
+ case LOG_FILE_COUNT:
+ try {
+ intValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (intValue < 1 || intValue > 100) {
+ messageMap.put(option, "Log file count range must be 1 to 100");
+ break;
+ }
+ setNode(LOG_FILE_COUNT, value, configFile, configElement);
+ setLogFileCount(Integer.parseInt(value));
+ break;
+ case STATUS_FREQUENCY:
+ try {
+ intValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (intValue < 1) {
+ messageMap.put(option, "Status update frequency must be greater than 1");
+ break;
+ }
+ setNode(STATUS_FREQUENCY, value, configFile, configElement);
+ setStatusFrequency(Integer.parseInt(value));
+ break;
+ case CHANGE_FREQUENCY:
+ try {
+ intValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (intValue < 1) {
+ messageMap.put(option, "Get changes frequency must be greater than 1");
+ break;
+ }
+ setNode(CHANGE_FREQUENCY, value, configFile, configElement);
+ setChangeFrequency(Integer.parseInt(value));
+ break;
+ case DEVICE_SCAN_FREQUENCY:
+ try {
+ intValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (intValue < 1) {
+ messageMap.put(option, "Get scan devices frequency must be greater than 1");
+ break;
+ }
+ setNode(DEVICE_SCAN_FREQUENCY, value, configFile, configElement);
+ setDeviceScanFrequency(Integer.parseInt(value));
+ break;
+ case POST_DIAGNOSTICS_FREQ:
+ try {
+ intValue = Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ messageMap.put(option, "Option -" + option + " has invalid value: " + value);
+ break;
+ }
+ if (intValue < 1) {
+ messageMap.put(option, "Post diagnostics frequency must be greater than 1");
+ break;
+ }
+ setNode(POST_DIAGNOSTICS_FREQ, value, configFile, configElement);
+ setPostDiagnosticsFreq(Integer.parseInt(value));
+ break;
+ case WATCHDOG_ENABLED:
+ setNode(WATCHDOG_ENABLED, value, configFile, configElement);
+ setWatchdogEnabled(!value.equals("off"));
+ break;
+ case GPS_COORDINATES:
+ configureGps(value);
+ writeGpsToConfigFile();
+ break;
+ case FOG_TYPE:
+ configureFogType(value);
+ setNode(FOG_TYPE, value, configFile, configElement);
+ break;
+ case DEV_MODE:
+ setNode(DEV_MODE, value, configFile, configElement);
+ setDeveloperMode(!value.equals("off"));
+ break;
+ default:
+ throw new ConfigurationItemException("Invalid parameter -" + option);
+ }
+ }
+ saveConfigUpdates();
+
+ return messageMap;
+ }
+
+ /**
+ * Configures fogType.
+ *
+ * @param fogTypeCommand could be "auto" or string that matches one of the {@link ArchitectureType} patterns
+ * @throws ConfigurationItemException if {@link ArchitectureType} undefined
+ */
+ private static void configureFogType(String fogTypeCommand) throws ConfigurationItemException {
+ ArchitectureType newFogType = ArchitectureType.UNDEFINED;
+ switch (fogTypeCommand) {
+ case "auto": {
+ newFogType = ArchitectureType.getArchTypeByArchName(System.getProperty("os.arch"));
+ break;
+ }
+ case "intel_amd": {
+ newFogType = ArchitectureType.INTEL_AMD;
+ break;
+ }
+ case "arm": {
+ newFogType = ArchitectureType.ARM;
+ break;
+ }
+ }
+
+ if (newFogType == ArchitectureType.UNDEFINED) {
+ throw new ConfigurationItemException("Couldn't autodetect fogType or unknown fogType type was set.");
+ }
+
+ setFogType(newFogType);
+ updateAutomaticConfigParams();
+ }
+
+ /**
+ * Configures GPS coordinates and mode in config file
+ *
+ * @param gpsCoordinatesCommand coordinates special command or lat,lon string (prefer using DD GPS format)
+ * @throws ConfigurationItemException
+ */
+ private static void configureGps(String gpsCoordinatesCommand) throws ConfigurationItemException {
+ String gpsCoordinates;
+ GpsMode currentMode;
+
+ if (GpsMode.AUTO.name().toLowerCase().equals(gpsCoordinatesCommand)) {
+ gpsCoordinates = GpsWebHandler.getGpsCoordinatesByExternalIp();
+ currentMode = GpsMode.AUTO;
+ } else if (GpsMode.OFF.name().toLowerCase().equals(gpsCoordinatesCommand)) {
+ gpsCoordinates = "";
+ currentMode = GpsMode.OFF;
+ } else {
+ gpsCoordinates = gpsCoordinatesCommand;
+ currentMode = GpsMode.MANUAL;
+ }
+
+ setGpsDataIfValid(currentMode, gpsCoordinates);
+ }
+
+ public static void setGpsDataIfValid(GpsMode mode, String gpsCoordinates) throws ConfigurationItemException {
+ if (!isValidCoordinates(gpsCoordinates)) {
+ throw new ConfigurationItemException("Incorrect GPS coordinates value: " + gpsCoordinates + "\n"
+ + "Correct format is (GPS DD format)");
+ }
+
+ setGpsCoordinates(gpsCoordinates.trim());
+ setGpsMode(mode);
+ }
+
+ /**
+ * Writes GPS coordinates and GPS mode to config file
+ *
+ * @throws ConfigurationItemException
+ */
+ public static void writeGpsToConfigFile() throws ConfigurationItemException {
+ if (gpsMode == GpsMode.MANUAL) {
+ setNode(GPS_COORDINATES, gpsCoordinates, configFile, configElement);
+ } else {
+ setNode(GPS_COORDINATES, gpsMode.name().toLowerCase(), configFile, configElement);
+ }
+ }
+
+ /**
+ * Checks is string a valid DD GPS coordinates
+ *
+ * @param gpsCoordinates
+ * @return
+ */
+ private static boolean isValidCoordinates(String gpsCoordinates) {
+
+ boolean isValid = true;
+
+ String fpRegex = "[+-]?[0-9]+(.?[0-9]+)?,?" +
+ "[+-]?[0-9]+(.?[0-9]+)?";
+
+ if (Pattern.matches(fpRegex, gpsCoordinates)) {
+
+ String[] latLon = gpsCoordinates.split(",");
+ double lat = Double.parseDouble(latLon[0]);
+ double lon = Double.parseDouble(latLon[1]);
+
+ if (lat > 90 || lat < -90 || lon > 180 || lon < -180) {
+ isValid = false;
+ }
+ } else {
+ isValid = gpsCoordinates.isEmpty();
+ }
+
+ return isValid;
+ }
+
+ /**
+ * checks if given network interface is valid
+ *
+ * @param eth - network interface
+ * @return
+ */
+ private static boolean isValidNetworkInterface(String eth) {
+ if (SystemUtils.IS_OS_WINDOWS) { // any name could be used for network interface on Win
+ return true;
+ }
+
+ try {
+ if (CommandLineConfigParam.NETWORK_INTERFACE.getDefaultValue().equals(eth)) {
+ return true;
+ }
+ Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
+ for (NetworkInterface networkInterface : list(networkInterfaces)) {
+ if (networkInterface.getName().equalsIgnoreCase(eth))
+ return true;
+ }
+ } catch (Exception e) {
+ logInfo(MODULE_NAME, "Error validating network interface : " + e.getMessage());
+ }
+ return false;
+ }
+
+ /**
+ * adds file separator to end of directory names, if not exists
+ *
+ * @param value - name of directory
+ * @return directory containing file separator at the end
+ */
+ private static String addSeparator(String value) {
+ if (value.charAt(value.length() - 1) == separatorChar)
+ return value;
+ else
+ return value + separatorChar;
+ }
+
+
+ /**
+ * loads configuration from config.xml file
+ *
+ * @throws Exception
+ */
+ public static void loadConfig() throws Exception {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder = factory.newDocumentBuilder();
+
+ configFile = builder.parse(getCurrentConfigPath());
+ configFile.getDocumentElement().normalize();
+
+ configElement = (Element) getFirstNodeByTagName("config", configFile);
+
+ setIofogUuid(getNode(IOFOG_UUID, configFile));
+ setAccessToken(getNode(ACCESS_TOKEN, configFile));
+ setControllerUrl(getNode(CONTROLLER_URL, configFile));
+ setControllerCert(getNode(CONTROLLER_CERT, configFile));
+ setNetworkInterface(getNode(NETWORK_INTERFACE, configFile));
+ setDockerUrl(getNode(DOCKER_URL, configFile));
+ setDiskLimit(Float.parseFloat(getNode(DISK_CONSUMPTION_LIMIT, configFile)));
+ setDiskDirectory(getNode(DISK_DIRECTORY, configFile));
+ setMemoryLimit(Float.parseFloat(getNode(MEMORY_CONSUMPTION_LIMIT, configFile)));
+ setCpuLimit(Float.parseFloat(getNode(PROCESSOR_CONSUMPTION_LIMIT, configFile)));
+ setLogDiskDirectory(getNode(LOG_DISK_DIRECTORY, configFile));
+ setLogDiskLimit(Float.parseFloat(getNode(LOG_DISK_CONSUMPTION_LIMIT, configFile)));
+ setLogFileCount(Integer.parseInt(getNode(LOG_FILE_COUNT, configFile)));
+ configureGps(getNode(GPS_COORDINATES, configFile));
+ setChangeFrequency(Integer.parseInt(getNode(CHANGE_FREQUENCY, configFile)));
+ setDeviceScanFrequency(Integer.parseInt(getNode(DEVICE_SCAN_FREQUENCY, configFile)));
+ setStatusFrequency(Integer.parseInt(getNode(STATUS_FREQUENCY, configFile)));
+ setPostDiagnosticsFreq(Integer.parseInt(getNode(POST_DIAGNOSTICS_FREQ, configFile)));
+ setWatchdogEnabled(!getNode(WATCHDOG_ENABLED, configFile).equals("off"));
+ configureFogType(getNode(FOG_TYPE, configFile));
+ setDeveloperMode(!getNode(DEV_MODE, configFile).equals("off"));
+
+ }
+
+ /**
+ * loads configuration about current config from config-switcher.xml
+ *
+ * @throws Exception
+ */
+ public static void loadConfigSwitcher() throws Exception {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder = factory.newDocumentBuilder();
+
+ configSwitcherFile = builder.parse(CONFIG_SWITCHER_PATH);
+ configSwitcherFile.getDocumentElement().normalize();
+
+ configSwitcherElement = (Element) getFirstNodeByTagName(SWITCHER_ELEMENT, configSwitcherFile);
+
+ verifySwitcherNode(SWITCHER_NODE, ConfigSwitcherState.DEFAULT.fullValue());
+ }
+
+ // this code will be triggered in case of iofog updated (not newly installed) and add new option for config
+ private static void createConfigProperty(CommandLineConfigParam cmdParam) throws Exception {
+ // TODO: add appropriate handling of case when 0 nodes found or multiple before adding new property to file
+ Element el = configFile.createElement(cmdParam.getXmlTag());
+ el.appendChild(configFile.createTextNode(cmdParam.getDefaultValue()));
+ configElement.appendChild(el);
+
+ DOMSource source = new DOMSource(configFile);
+ TransformerFactory transformerFactory = TransformerFactory.newInstance();
+ Transformer transformer = transformerFactory.newTransformer();
+ StreamResult result = new StreamResult(getCurrentConfigPath());
+ transformer.transform(source, result);
+ }
+
+ public static String getAccessToken() {
+ return accessToken;
+ }
+
+ public static String getControllerUrl() {
+ return controllerUrl;
+ }
+
+ public static String getControllerCert() {
+ return controllerCert;
+ }
+
+ public static String getNetworkInterface() {
+ return networkInterface;
+ }
+
+ public static String getDockerUrl() {
+ return dockerUrl;
+ }
+
+ public static float getDiskLimit() {
+ return diskLimit;
+ }
+
+ public static float getMemoryLimit() {
+ return memoryLimit;
+ }
+
+ public static String getDiskDirectory() {
+ return diskDirectory;
+ }
+
+ public static float getCpuLimit() {
+ return cpuLimit;
+ }
+
+ public static String getIofogUuid() {
+ return iofogUuid;
+ }
+
+ public static int getLogFileCount() {
+ return logFileCount;
+ }
+
+ public static float getLogDiskLimit() {
+ return logDiskLimit;
+ }
+
+ public static String getLogDiskDirectory() {
+ return logDiskDirectory;
+ }
+
+ public static void setLogDiskDirectory(String logDiskDirectory) {
+ if (logDiskDirectory.charAt(0) != separatorChar)
+ logDiskDirectory = separatorChar + logDiskDirectory;
+ if (logDiskDirectory.charAt(logDiskDirectory.length() - 1) != separatorChar)
+ logDiskDirectory += separatorChar;
+ Configuration.logDiskDirectory = SNAP_COMMON + logDiskDirectory;
+ }
+
+ public static void setAccessToken(String accessToken) throws ConfigurationItemException {
+ setNode(ACCESS_TOKEN, accessToken, configFile, configElement);
+ Configuration.accessToken = accessToken;
+ }
+
+ public static void setIofogUuid(String iofogUuid) throws ConfigurationItemException {
+ setNode(IOFOG_UUID, iofogUuid, configFile, configElement);
+ Configuration.iofogUuid = iofogUuid;
+ }
+
+ private static void verifySwitcherNode(String switcher, String defaultValue) throws ConfigurationItemException {
+ NodeList nodes = configSwitcherElement.getElementsByTagName(switcher);
+ if (nodes.getLength() == 0) {
+ configSwitcherElement.appendChild(configSwitcherFile.createElement(switcher));
+ getFirstNodeByTagName(switcher, configSwitcherFile).setTextContent(defaultValue);
+ currentSwitcherState = ConfigSwitcherState.DEFAULT;
+ } else {
+ String currentState = getFirstNodeByTagName(switcher, configSwitcherFile).getTextContent();
+ try {
+ currentSwitcherState = ConfigSwitcherState.parse(currentState);
+ } catch (IllegalArgumentException e) {
+ currentSwitcherState = ConfigSwitcherState.DEFAULT;
+ System.out.println("Error while reading current switcher state, using default config");
+ }
+ }
+ }
+
+ private static void setControllerUrl(String controllerUrl) {
+ if (controllerUrl != null && controllerUrl.length() > 0 && controllerUrl.charAt(controllerUrl.length() - 1) != '/')
+ controllerUrl += '/';
+ Configuration.controllerUrl = controllerUrl;
+ }
+
+ private static void setControllerCert(String controllerCert) {
+ Configuration.controllerCert = SNAP_COMMON + controllerCert;
+ }
+
+ private static void setNetworkInterface(String networkInterface) {
+ Configuration.networkInterface = networkInterface;
+ }
+
+ private static void setDockerUrl(String dockerUrl) {
+ Configuration.dockerUrl = dockerUrl;
+ }
+
+ private static void setDiskLimit(float diskLimit) {
+ Configuration.diskLimit = diskLimit;
+ }
+
+ private static void setMemoryLimit(float memoryLimit) {
+ Configuration.memoryLimit = memoryLimit;
+ }
+
+ private static void setDiskDirectory(String diskDirectory) {
+ if (diskDirectory.charAt(0) != separatorChar)
+ diskDirectory = separatorChar + diskDirectory;
+ if (diskDirectory.charAt(diskDirectory.length() - 1) != separatorChar)
+ diskDirectory += separatorChar;
+ Configuration.diskDirectory = SNAP_COMMON + diskDirectory;
+ }
+
+ private static void setCpuLimit(float cpuLimit) {
+ Configuration.cpuLimit = cpuLimit;
+ }
+
+ private static void setLogDiskLimit(float logDiskLimit) {
+ Configuration.logDiskLimit = logDiskLimit;
+ }
+
+ private static void setLogFileCount(int logFileCount) {
+ Configuration.logFileCount = logFileCount;
+ }
+
+ /**
+ * returns report for "info" commandline parameter
+ *
+ * @return info report
+ */
+ public static String getConfigReport() {
+ String ipAddress = IOFogNetworkInterface.getCurrentIpAddress();
+ String networkInterface = getNetworkInterfaceInfo();
+ ipAddress = "".equals(ipAddress) ? "unable to retrieve ip address" : ipAddress;
+
+ StringBuilder result = new StringBuilder();
+ // iofog UUID
+ result.append(buildReportLine(getIofogUuidMessage(), isNotBlank(iofogUuid) ? iofogUuid : "not provisioned"));
+ //ip address
+ result.append(buildReportLine(getIpAddressMessage(), ipAddress));
+ // network interface
+ result.append(buildReportLine(getConfigParamMessage(NETWORK_INTERFACE), networkInterface));
+ // developer mode
+ result.append(buildReportLine(getConfigParamMessage(DEV_MODE), (developerMode ? "on" : "off")));
+ // controller url
+ result.append(buildReportLine(getConfigParamMessage(CONTROLLER_URL), controllerUrl));
+ // controller cert dir
+ result.append(buildReportLine(getConfigParamMessage(CONTROLLER_CERT), controllerCert));
+ // docker url
+ result.append(buildReportLine(getConfigParamMessage(DOCKER_URL), dockerUrl));
+ // disk usage limit
+ result.append(buildReportLine(getConfigParamMessage(DISK_CONSUMPTION_LIMIT), format("%.2f GiB", diskLimit)));
+ // disk directory
+ result.append(buildReportLine(getConfigParamMessage(DISK_DIRECTORY), diskDirectory));
+ // memory ram limit
+ result.append(buildReportLine(getConfigParamMessage(MEMORY_CONSUMPTION_LIMIT), format("%.2f MiB", memoryLimit)));
+ // cpu usage limit
+ result.append(buildReportLine(getConfigParamMessage(PROCESSOR_CONSUMPTION_LIMIT), format("%.2f%%", cpuLimit)));
+ // log disk limit
+ result.append(buildReportLine(getConfigParamMessage(LOG_DISK_CONSUMPTION_LIMIT), format("%.2f GiB", logDiskLimit)));
+ // log file directory
+ result.append(buildReportLine(getConfigParamMessage(LOG_DISK_DIRECTORY), logDiskDirectory));
+ // log files count
+ result.append(buildReportLine(getConfigParamMessage(LOG_FILE_COUNT), format("%d", logFileCount)));
+ // status update frequency
+ result.append(buildReportLine(getConfigParamMessage(STATUS_FREQUENCY), format("%d", statusFrequency)));
+ // status update frequency
+ result.append(buildReportLine(getConfigParamMessage(CHANGE_FREQUENCY), format("%d", changeFrequency)));
+ // scan devices frequency
+ result.append(buildReportLine(getConfigParamMessage(DEVICE_SCAN_FREQUENCY), format("%d", deviceScanFrequency)));
+ // post diagnostics frequency
+ result.append(buildReportLine(getConfigParamMessage(POST_DIAGNOSTICS_FREQ), format("%d", postDiagnosticsFreq)));
+ // log file directory
+ result.append(buildReportLine(getConfigParamMessage(WATCHDOG_ENABLED), (watchdogEnabled ? "on" : "off")));
+ // gps mode
+ result.append(buildReportLine(getConfigParamMessage(GPS_MODE), gpsMode.name().toLowerCase()));
+ // gps coordinates
+ result.append(buildReportLine(getConfigParamMessage(GPS_COORDINATES), gpsCoordinates));
+ //fog type
+ result.append(buildReportLine(getConfigParamMessage(FOG_TYPE), fogType.name().toLowerCase()));
+
+ return result.toString();
+ }
+
+ private static String buildReportLine(String messageDescription, String value) {
+ return rightPad(messageDescription, 40, ' ') + " : " + value + "\\n";
+ }
+
+ private static String getNetworkInterfaceInfo() {
+ return NETWORK_INTERFACE.getDefaultValue().equals(networkInterface) ?
+ IOFogNetworkInterface.getNetworkInterface() + "(" + NETWORK_INTERFACE.getDefaultValue() + ")" :
+ networkInterface;
+ }
+
+ public static Document getCurrentConfig() {
+ return configFile;
+ }
+
+ public static String getCurrentConfigPath() {
+ switch (currentSwitcherState) {
+ case DEVELOPMENT:
+ return Constants.DEVELOPMENT_CONFIG_PATH;
+ case PRODUCTION:
+ return Constants.PRODUCTION_CONFIG_PATH;
+ case DEFAULT:
+ default:
+ return Constants.DEFAULT_CONFIG_PATH;
+ }
+ }
+
+ public static String setupConfigSwitcher(ConfigSwitcherState state) {
+ ConfigSwitcherState previousState = currentSwitcherState;
+ if (state.equals(previousState)) {
+ return "Already using this configuration.";
+ }
+ return reload(state, previousState);
+ }
+
+ /**
+ * loads config-switcher.xml and config-*.xml file
+ */
+ public static void load() {
+ try {
+ Configuration.loadConfigSwitcher();
+ } catch (Exception e) {
+ System.out.println("Error while parsing " + Constants.CONFIG_SWITCHER_PATH + ". " + e.getMessage());
+ System.exit(1);
+ }
+
+ try {
+ Configuration.loadConfig();
+ } catch (ConfigurationItemException e) {
+ System.out.println("invalid configuration item(s).");
+ System.out.println(e.getMessage());
+ System.exit(1);
+ } catch (Exception e) {
+ System.out.println("Error while parsing " + Configuration.getCurrentConfigPath() + ". " + e.getMessage());
+ System.exit(1);
+ }
+
+ }
+
+ private static String reload(ConfigSwitcherState newState, ConfigSwitcherState previousState) {
+ try {
+ getFirstNodeByTagName(SWITCHER_NODE, configSwitcherFile).setTextContent(newState.fullValue());
+ updateConfigFile(CONFIG_SWITCHER_PATH, configSwitcherFile);
+
+ Configuration.loadConfigSwitcher();
+ Configuration.loadConfig();
+
+ FieldAgent.getInstance().instanceConfigUpdated();
+ ProcessManager.getInstance().instanceConfigUpdated();
+ ResourceConsumptionManager.getInstance().instanceConfigUpdated();
+ LoggingService.instanceConfigUpdated();
+ MessageBus.getInstance().instanceConfigUpdated();
+
+ return "Successfully switched to new configuration.";
+ } catch (Exception e) {
+ try {
+ getFirstNodeByTagName(SWITCHER_NODE, configSwitcherFile).setTextContent(previousState.fullValue());
+ updateConfigFile(CONFIG_SWITCHER_PATH, configSwitcherFile);
+
+ load();
+
+ FieldAgent.getInstance().instanceConfigUpdated();
+ ProcessManager.getInstance().instanceConfigUpdated();
+ ResourceConsumptionManager.getInstance().instanceConfigUpdated();
+ LoggingService.instanceConfigUpdated();
+ MessageBus.getInstance().instanceConfigUpdated();
+
+ return "Error while loading new config file, falling back to current configuration";
+ } catch (Exception fatalException) {
+ System.out.println("Error while loading previous configuration, try to restart iofog-agent");
+ System.exit(1);
+ return "";
+ }
+ }
+ }
+
+ public static void setupSupervisor() {
+ LoggingService.logInfo(MODULE_NAME, "starting supervisor");
+ try {
+ Supervisor supervisor = new Supervisor();
+ supervisor.start();
+ } catch (Exception exp) {
+ LoggingService.logWarning(MODULE_NAME, exp.getMessage());
+ }
+ }
}
\ No newline at end of file
diff --git a/daemon/src/org/eclipse/iofog/utils/logging/LoggingService.java b/daemon/src/org/eclipse/iofog/utils/logging/LoggingService.java
index d2df319d..d071f1c2 100755
--- a/daemon/src/org/eclipse/iofog/utils/logging/LoggingService.java
+++ b/daemon/src/org/eclipse/iofog/utils/logging/LoggingService.java
@@ -133,7 +133,7 @@ public static void setupMicroserviceLogger(String microserviceUuid, long logSize
logDirectory.mkdirs();
UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();
- final GroupPrincipal group = lookupservice.lookupPrincipalByGroupName("iofog");
+ final GroupPrincipal group = lookupservice.lookupPrincipalByGroupName(Constants.OS_GROUP);
if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC) {
PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(logDirectory.toPath(), PosixFileAttributeView.class,
LinkOption.NOFOLLOW_LINKS);
diff --git a/iofog-agent-packaging-rpm/etc/iofog-agent/config-development_new.xml b/iofog-agent-packaging-rpm/etc/iofog-agent/config-development_new.xml
new file mode 100644
index 00000000..77364497
--- /dev/null
+++ b/iofog-agent-packaging-rpm/etc/iofog-agent/config-development_new.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+ http://localhost:51121/api/v3/
+
+
+
+ on
+
+ /etc/iofog-agent/cert.crt
+
+ auto
+
+ dynamic
+
+ unix:///var/run/docker.sock
+
+ 50
+
+ /var/lib/iofog-agent/
+
+ 4096
+
+ 80.0
+
+ 10.0
+
+ /var/log/iofog-agent/
+
+ 10
+
+ 30
+
+ 60
+
+ 10
+
+ 60
+
+ auto
+
diff --git a/iofog-agent-packaging-rpm/etc/iofog-agent/config-production_new.xml b/iofog-agent-packaging-rpm/etc/iofog-agent/config-production_new.xml
new file mode 100644
index 00000000..9155a7d2
--- /dev/null
+++ b/iofog-agent-packaging-rpm/etc/iofog-agent/config-production_new.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+ http://localhost:54421/api/v3/
+
+
+
+ off
+
+ /etc/iofog-agent/cert.crt
+
+ auto
+
+ dynamic
+
+ unix:///var/run/docker.sock
+
+ 50
+
+ /var/lib/iofog-agent/
+
+ 4096
+
+ 80.0
+
+ 10.0
+
+ /var/log/iofog-agent/
+
+ 10
+
+ 30
+
+ 60
+
+ 10
+
+ 60
+
+ auto
+
diff --git a/iofog-agent-packaging-rpm/etc/iofog-agent/config-switcher_new.xml b/iofog-agent-packaging-rpm/etc/iofog-agent/config-switcher_new.xml
new file mode 100644
index 00000000..85714208
--- /dev/null
+++ b/iofog-agent-packaging-rpm/etc/iofog-agent/config-switcher_new.xml
@@ -0,0 +1,17 @@
+
+
+
+
+ default
+
\ No newline at end of file
diff --git a/iofog-agent-packaging-rpm/rpm.sh b/iofog-agent-packaging-rpm/rpm.sh
index adab96ca..79cc6bca 100644
--- a/iofog-agent-packaging-rpm/rpm.sh
+++ b/iofog-agent-packaging-rpm/rpm.sh
@@ -16,6 +16,30 @@ else
fi
#echo "Check for config.xml"
+if [ -f /etc/iofog-agent/config-development.xml ];
+then
+ rm /etc/iofog-agent/config-development_new.xml
+else
+ mv /etc/iofog-agent/config-development_new.xml /etc/iofog-agent/config-development.xml
+fi
+#echo "Check for config-development.xml"
+
+if [ -f /etc/iofog-agent/config-production.xml ];
+then
+ rm /etc/iofog-agent/config-production_new.xml
+else
+ mv /etc/iofog-agent/config-production_new.xml /etc/iofog-agent/config-production.xml
+fi
+#echo "Check for config-production.xml"
+
+if [ -f /etc/iofog-agent/config-switcher.xml ];
+then
+ rm /etc/iofog-agent/config-switcher_new.xml
+else
+ mv /etc/iofog-agent/config-switcher_new.xml /etc/iofog-agent/config-switcher.xml
+fi
+#echo "Check for config-switcher.xml"
+
if [ -f /etc/iofog-agent/cert.crt ];
then
rm /etc/iofog-agent/cert_new.crt
diff --git a/iofog-agent-packaging/debian.sh b/iofog-agent-packaging/debian.sh
index af1fd15b..e40ac454 100644
--- a/iofog-agent-packaging/debian.sh
+++ b/iofog-agent-packaging/debian.sh
@@ -13,6 +13,30 @@ else
fi
echo "Check for config.xml"
+if [ -f /etc/iofog-agent/config-development.xml ];
+then
+ rm /etc/iofog-agent/config-development_new.xml
+else
+ mv /etc/iofog-agent/config-development_new.xml /etc/iofog-agent/config-development.xml
+fi
+#echo "Check for config-development.xml"
+
+if [ -f /etc/iofog-agent/config-production.xml ];
+then
+ rm /etc/iofog-agent/config-production_new.xml
+else
+ mv /etc/iofog-agent/config-production_new.xml /etc/iofog-agent/config-production.xml
+fi
+#echo "Check for config-production.xml"
+
+if [ -f /etc/iofog-agent/config-switcher.xml ];
+then
+ rm /etc/iofog-agent/config-switcher_new.xml
+else
+ mv /etc/iofog-agent/config-switcher_new.xml /etc/iofog-agent/config-switcher.xml
+fi
+#echo "Check for config-switcher.xml"
+
if [ -f /etc/iofog-agent/cert.crt ];
then
rm /etc/iofog-agent/cert_new.crt
diff --git a/iofog-agent-packaging/etc/iofog-agent/config-development_new.xml b/iofog-agent-packaging/etc/iofog-agent/config-development_new.xml
new file mode 100644
index 00000000..77364497
--- /dev/null
+++ b/iofog-agent-packaging/etc/iofog-agent/config-development_new.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+ http://localhost:51121/api/v3/
+
+
+
+ on
+
+ /etc/iofog-agent/cert.crt
+
+ auto
+
+ dynamic
+
+ unix:///var/run/docker.sock
+
+ 50
+
+ /var/lib/iofog-agent/
+
+ 4096
+
+ 80.0
+
+ 10.0
+
+ /var/log/iofog-agent/
+
+ 10
+
+ 30
+
+ 60
+
+ 10
+
+ 60
+
+ auto
+
diff --git a/iofog-agent-packaging/etc/iofog-agent/config-production_new.xml b/iofog-agent-packaging/etc/iofog-agent/config-production_new.xml
new file mode 100644
index 00000000..9155a7d2
--- /dev/null
+++ b/iofog-agent-packaging/etc/iofog-agent/config-production_new.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+ http://localhost:54421/api/v3/
+
+
+
+ off
+
+ /etc/iofog-agent/cert.crt
+
+ auto
+
+ dynamic
+
+ unix:///var/run/docker.sock
+
+ 50
+
+ /var/lib/iofog-agent/
+
+ 4096
+
+ 80.0
+
+ 10.0
+
+ /var/log/iofog-agent/
+
+ 10
+
+ 30
+
+ 60
+
+ 10
+
+ 60
+
+ auto
+
diff --git a/iofog-agent-packaging/etc/iofog-agent/config-switcher_new.xml b/iofog-agent-packaging/etc/iofog-agent/config-switcher_new.xml
new file mode 100644
index 00000000..85714208
--- /dev/null
+++ b/iofog-agent-packaging/etc/iofog-agent/config-switcher_new.xml
@@ -0,0 +1,17 @@
+
+
+
+
+ default
+
\ No newline at end of file
diff --git a/iofog_version_controller/pom.xml b/iofog_version_controller/pom.xml
index a6d2cd0f..afd0f449 100644
--- a/iofog_version_controller/pom.xml
+++ b/iofog_version_controller/pom.xml
@@ -16,7 +16,7 @@
iofog-agent
org.eclipse
- 1.0.3
+ 1.0.4
4.0.0
diff --git a/pom.xml b/pom.xml
index bebbaf29..dcbe0d3b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -15,7 +15,7 @@
4.0.0
org.eclipse
iofog-agent
- 1.0.3
+ 1.0.4
iofog-agent
pom